
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_Hans">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>模型字段参考 &#8212; Django 3.2.6.dev 文档</title>
    <link rel="stylesheet" href="../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../_static/underscore.js"></script>
    <script type="text/javascript" src="../../_static/doctools.js"></script>
    <script type="text/javascript" src="../../_static/language_data.js"></script>
    <link rel="index" title="索引" href="../../genindex.html" />
    <link rel="search" title="搜索" href="../../search.html" />
    <link rel="next" title="模型索引参考" href="indexes.html" />
    <link rel="prev" title="模型" href="index.html" />



 
<script src="../../templatebuiltins.js"></script>
<script>
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);</script>

  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../../index.html">Django 3.2.6.dev 文档</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../../index.html">Home</a>  |
        <a title="Table of contents" href="../../contents.html">Table of contents</a>  |
        <a title="Global index" href="../../genindex.html">Index</a>  |
        <a title="Module index" href="../../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="index.html" title="模型">previous</a>
     |
    <a href="../index.html" title="API 参考" accesskey="U">up</a>
   |
    <a href="indexes.html" title="模型索引参考">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="ref-models-fields">
            
  <div class="section" id="s-module-django.db.models.fields">
<span id="s-model-field-reference"></span><span id="module-django.db.models.fields"></span><span id="model-field-reference"></span><h1>模型字段参考<a class="headerlink" href="#module-django.db.models.fields" title="永久链接至标题">¶</a></h1>
<p>本文档包含 <a class="reference internal" href="#django.db.models.Field" title="django.db.models.Field"><code class="xref py py-class docutils literal notranslate"><span class="pre">Field</span></code></a> 类的所有 API 参考，包括 <a class="reference internal" href="#field-options">字段选项</a> 和 <a class="reference internal" href="#field-types">字段类型</a>。</p>
<div class="admonition seealso">
<p class="first admonition-title">参见</p>
<p>若内置字段未满足需求，你可以试试 <a class="reference external" href="https://github.com/django/django-localflavor">django-localflavor</a> （ <a class="reference external" href="https://django-localflavor.readthedocs.io/">文档</a> ），它包含了针对各别国家和文件的代码。</p>
<p class="last">当然，你也可以简单的 <a class="reference internal" href="../../howto/custom-model-fields.html"><span class="doc">编写自定义模型字段</span></a>。</p>
</div>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">从技术上讲，这些方法都被定义在 <a class="reference internal" href="#module-django.db.models.fields" title="django.db.models.fields: Built-in field types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">django.db.models.fields</span></code></a>，但为了方便，它们被导入到 <a class="reference internal" href="../../topics/db/models.html#module-django.db.models" title="django.db.models"><code class="xref py py-mod docutils literal notranslate"><span class="pre">django.db.models</span></code></a>；标准的惯例是使用 <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">django.db</span> <span class="pre">import</span> <span class="pre">models</span></code> 并利用 <code class="docutils literal notranslate"><span class="pre">models.&lt;Foo&gt;Field</span></code>。</p>
</div>
<div class="section" id="s-field-options">
<span id="s-common-model-field-options"></span><span id="field-options"></span><span id="common-model-field-options"></span><h2>字段选项<a class="headerlink" href="#field-options" title="永久链接至标题">¶</a></h2>
<p>以下参数对所以字段类型均有效，且是可选的。</p>
<div class="section" id="s-null">
<span id="null"></span><h3><code class="docutils literal notranslate"><span class="pre">null</span></code><a class="headerlink" href="#null" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.db.models.Field.null">
<code class="descclassname">Field.</code><code class="descname">null</code><a class="headerlink" href="#django.db.models.Field.null" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>如果是 <code class="docutils literal notranslate"><span class="pre">True</span></code>， Django 将在数据库中存储空值为 <code class="docutils literal notranslate"><span class="pre">NULL</span></code>。默认为 <code class="docutils literal notranslate"><span class="pre">False</span></code>。</p>
<p>避免在基于字符串的字段上使用 <a class="reference internal" href="#django.db.models.Field.null" title="django.db.models.Field.null"><code class="xref py py-attr docutils literal notranslate"><span class="pre">null</span></code></a>，如 <a class="reference internal" href="#django.db.models.CharField" title="django.db.models.CharField"><code class="xref py py-class docutils literal notranslate"><span class="pre">CharField</span></code></a> 和 <a class="reference internal" href="#django.db.models.TextField" title="django.db.models.TextField"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextField</span></code></a>。如果一个基于字符串的字段有 <code class="docutils literal notranslate"><span class="pre">null=True</span></code>，这意味着它有两种可能的“无数据”值。<code class="docutils literal notranslate"><span class="pre">NULL</span></code>，和空字符串。在大多数情况下，“无数据”有两种可能的值是多余的，Django 的惯例是使用空字符串，而不是 <code class="docutils literal notranslate"><span class="pre">NULL</span></code>。一个例外是当一个 <a class="reference internal" href="#django.db.models.CharField" title="django.db.models.CharField"><code class="xref py py-class docutils literal notranslate"><span class="pre">CharField</span></code></a> 同时设置了 <code class="docutils literal notranslate"><span class="pre">unique=True</span></code> 和 <code class="docutils literal notranslate"><span class="pre">blank=True</span></code>。在这种情况下，<code class="docutils literal notranslate"><span class="pre">null=True</span></code> 是需要的，以避免在保存具有空白值的多个对象时违反唯一约束。</p>
<p>无论是基于字符串的字段还是非字符串的字段，如果希望在表单中允许空值，还需要设置 <code class="docutils literal notranslate"><span class="pre">blank=True</span></code>，因为 <a class="reference internal" href="#django.db.models.Field.null" title="django.db.models.Field.null"><code class="xref py py-attr docutils literal notranslate"><span class="pre">null</span></code></a> 参数只影响数据库的存储（参见 <a class="reference internal" href="#django.db.models.Field.blank" title="django.db.models.Field.blank"><code class="xref py py-attr docutils literal notranslate"><span class="pre">blank</span></code></a> ）。</p>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">当使用 Oracle 数据库后端时，不管这个属性是什么，都会存储 <code class="docutils literal notranslate"><span class="pre">NULL</span></code> 值来表示空字符串。</p>
</div>
</div>
<div class="section" id="s-blank">
<span id="blank"></span><h3><code class="docutils literal notranslate"><span class="pre">blank</span></code><a class="headerlink" href="#blank" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.db.models.Field.blank">
<code class="descclassname">Field.</code><code class="descname">blank</code><a class="headerlink" href="#django.db.models.Field.blank" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>如果是 <code class="docutils literal notranslate"><span class="pre">True</span></code> ，该字段允许为空。默认为 <code class="docutils literal notranslate"><span class="pre">False</span></code> 。</p>
<p>注意，这与 <a class="reference internal" href="#django.db.models.Field.null" title="django.db.models.Field.null"><code class="xref py py-attr docutils literal notranslate"><span class="pre">null</span></code></a> 不同。 <a class="reference internal" href="#django.db.models.Field.null" title="django.db.models.Field.null"><code class="xref py py-attr docutils literal notranslate"><span class="pre">null</span></code></a> 纯属数据库相关，而 <a class="reference internal" href="#django.db.models.Field.blank" title="django.db.models.Field.blank"><code class="xref py py-attr docutils literal notranslate"><span class="pre">blank</span></code></a> 则与验证相关。如果一个字段有 <code class="docutils literal notranslate"><span class="pre">blank=True</span></code>，表单验证将允许输入一个空值。如果一个字段有 <code class="docutils literal notranslate"><span class="pre">blank=False</span></code>，则该字段为必填字段。</p>
</div>
<div class="section" id="s-choices">
<span id="s-field-choices"></span><span id="choices"></span><span id="field-choices"></span><h3><code class="docutils literal notranslate"><span class="pre">choices</span></code><a class="headerlink" href="#choices" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.db.models.Field.choices">
<code class="descclassname">Field.</code><code class="descname">choices</code><a class="headerlink" href="#django.db.models.Field.choices" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>一个 <a class="reference external" href="https://docs.python.org/3/glossary.html#term-sequence" title="(在 Python v3.9)"><span class="xref std std-term">sequence</span></a> 本身由正好两个项目的迭代项组成（例如 <code class="docutils literal notranslate"><span class="pre">[(A，B)，(A，B)...]</span></code> ），作为该字段的选择。如果给定了选择，它们会被 <a class="reference internal" href="instances.html#validating-objects"><span class="std std-ref">模型验证</span></a> 强制执行，默认的表单部件将是一个带有这些选择的选择框，而不是标准的文本字段。</p>
<p>每个元组中的第一个元素是要在模型上设置的实际值，第二个元素是人可读的名称。例如：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">YEAR_IN_SCHOOL_CHOICES</span> <span class="o">=</span> <span class="p">[</span>
    <span class="p">(</span><span class="s1">&#39;FR&#39;</span><span class="p">,</span> <span class="s1">&#39;Freshman&#39;</span><span class="p">),</span>
    <span class="p">(</span><span class="s1">&#39;SO&#39;</span><span class="p">,</span> <span class="s1">&#39;Sophomore&#39;</span><span class="p">),</span>
    <span class="p">(</span><span class="s1">&#39;JR&#39;</span><span class="p">,</span> <span class="s1">&#39;Junior&#39;</span><span class="p">),</span>
    <span class="p">(</span><span class="s1">&#39;SR&#39;</span><span class="p">,</span> <span class="s1">&#39;Senior&#39;</span><span class="p">),</span>
    <span class="p">(</span><span class="s1">&#39;GR&#39;</span><span class="p">,</span> <span class="s1">&#39;Graduate&#39;</span><span class="p">),</span>
<span class="p">]</span>
</pre></div>
</div>
<p>一般来说，最好在模型类内部定义选择，并为每个值定义一个合适的名称的常量：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Student</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">FRESHMAN</span> <span class="o">=</span> <span class="s1">&#39;FR&#39;</span>
    <span class="n">SOPHOMORE</span> <span class="o">=</span> <span class="s1">&#39;SO&#39;</span>
    <span class="n">JUNIOR</span> <span class="o">=</span> <span class="s1">&#39;JR&#39;</span>
    <span class="n">SENIOR</span> <span class="o">=</span> <span class="s1">&#39;SR&#39;</span>
    <span class="n">GRADUATE</span> <span class="o">=</span> <span class="s1">&#39;GR&#39;</span>
    <span class="n">YEAR_IN_SCHOOL_CHOICES</span> <span class="o">=</span> <span class="p">[</span>
        <span class="p">(</span><span class="n">FRESHMAN</span><span class="p">,</span> <span class="s1">&#39;Freshman&#39;</span><span class="p">),</span>
        <span class="p">(</span><span class="n">SOPHOMORE</span><span class="p">,</span> <span class="s1">&#39;Sophomore&#39;</span><span class="p">),</span>
        <span class="p">(</span><span class="n">JUNIOR</span><span class="p">,</span> <span class="s1">&#39;Junior&#39;</span><span class="p">),</span>
        <span class="p">(</span><span class="n">SENIOR</span><span class="p">,</span> <span class="s1">&#39;Senior&#39;</span><span class="p">),</span>
        <span class="p">(</span><span class="n">GRADUATE</span><span class="p">,</span> <span class="s1">&#39;Graduate&#39;</span><span class="p">),</span>
    <span class="p">]</span>
    <span class="n">year_in_school</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span>
        <span class="n">max_length</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span>
        <span class="n">choices</span><span class="o">=</span><span class="n">YEAR_IN_SCHOOL_CHOICES</span><span class="p">,</span>
        <span class="n">default</span><span class="o">=</span><span class="n">FRESHMAN</span><span class="p">,</span>
    <span class="p">)</span>

    <span class="k">def</span> <span class="nf">is_upperclass</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">year_in_school</span> <span class="ow">in</span> <span class="p">{</span><span class="bp">self</span><span class="o">.</span><span class="n">JUNIOR</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">SENIOR</span><span class="p">}</span>
</pre></div>
</div>
<p>虽然你可以在模型类之外定义一个选择列表，然后引用它，但在模型类内定义选择和每个选择的名称，可以将所有这些信息保留在使用它的类中，并帮助引用这些选择（例如，<code class="docutils literal notranslate"><span class="pre">Student.SOPHOMORE</span></code> 将在导入 <code class="docutils literal notranslate"><span class="pre">Student</span></code> 模型的任何地方工作）。</p>
<p id="field-choices-named-groups">你还可以将你的可用选择收集到可用于组织目的的命名组中：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">MEDIA_CHOICES</span> <span class="o">=</span> <span class="p">[</span>
    <span class="p">(</span><span class="s1">&#39;Audio&#39;</span><span class="p">,</span> <span class="p">(</span>
            <span class="p">(</span><span class="s1">&#39;vinyl&#39;</span><span class="p">,</span> <span class="s1">&#39;Vinyl&#39;</span><span class="p">),</span>
            <span class="p">(</span><span class="s1">&#39;cd&#39;</span><span class="p">,</span> <span class="s1">&#39;CD&#39;</span><span class="p">),</span>
        <span class="p">)</span>
    <span class="p">),</span>
    <span class="p">(</span><span class="s1">&#39;Video&#39;</span><span class="p">,</span> <span class="p">(</span>
            <span class="p">(</span><span class="s1">&#39;vhs&#39;</span><span class="p">,</span> <span class="s1">&#39;VHS Tape&#39;</span><span class="p">),</span>
            <span class="p">(</span><span class="s1">&#39;dvd&#39;</span><span class="p">,</span> <span class="s1">&#39;DVD&#39;</span><span class="p">),</span>
        <span class="p">)</span>
    <span class="p">),</span>
    <span class="p">(</span><span class="s1">&#39;unknown&#39;</span><span class="p">,</span> <span class="s1">&#39;Unknown&#39;</span><span class="p">),</span>
<span class="p">]</span>
</pre></div>
</div>
<p>每个元组中的第一个元素是应用于该组的名称。第二个元素是一个二元元组的迭代，每个二元元组包含一个值和一个可读的选项名称。分组后的选项可与未分组的选项结合在一个单一的列表中（如本例中的 <code class="docutils literal notranslate"><span class="pre">'unknown'</span></code> 选项）。</p>
<p>对于每一个设置了 <code class="xref py py-attr docutils literal notranslate"><span class="pre">choice</span></code> 的模型字段，Django 会添加一个方法来检索字段当前值的可读名称。参见数据库 API 文档中的 <a class="reference internal" href="instances.html#django.db.models.Model.get_FOO_display" title="django.db.models.Model.get_FOO_display"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_FOO_display()</span></code></a>。</p>
<p>请注意，选择可以是任何序列对象——不一定是列表或元组。这让你可以动态地构造选择。但是如果你发现自己把 <code class="xref py py-attr docutils literal notranslate"><span class="pre">chips</span></code> 魔改成动态的，你可能最好使用一个合适的的带有 <a class="reference internal" href="#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a> 的数据库表。 <code class="xref py py-attr docutils literal notranslate"><span class="pre">chips</span></code> 是用于静态数据的，如果有的话，不应该有太大的变化。</p>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">每当 <code class="docutils literal notranslate"><span class="pre">choices</span></code> 的顺序变动时将会创建新的迁移。</p>
</div>
<p id="field-choices-blank-label">除非 <a class="reference internal" href="#django.db.models.Field.blank" title="django.db.models.Field.blank"><code class="xref py py-attr docutils literal notranslate"><span class="pre">blank=False</span></code></a> 与 <a class="reference internal" href="#django.db.models.Field.default" title="django.db.models.Field.default"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default</span></code></a> 一起设置在字段上，否则包含 <code class="docutils literal notranslate"><span class="pre">&quot;---------&quot;</span></code> 的标签将与选择框一起呈现。要覆盖这种行为，可以在 <code class="docutils literal notranslate"><span class="pre">choices</span></code> 中添加一个包含 <code class="docutils literal notranslate"><span class="pre">None</span></code> 的元组，例如 <code class="docutils literal notranslate"><span class="pre">(None,</span> <span class="pre">'Your</span> <span class="pre">String</span> <span class="pre">For</span> <span class="pre">Display')</span></code> 。另外，你也可以在有意义的地方使用一个空字符串来代替 <code class="docutils literal notranslate"><span class="pre">None</span></code> ——比如在 <a class="reference internal" href="#django.db.models.CharField" title="django.db.models.CharField"><code class="xref py py-class docutils literal notranslate"><span class="pre">CharField</span></code></a>。</p>
<div class="section" id="s-enumeration-types">
<span id="s-field-choices-enum-types"></span><span id="enumeration-types"></span><span id="field-choices-enum-types"></span><h4>枚举类型<a class="headerlink" href="#enumeration-types" title="永久链接至标题">¶</a></h4>
<p>此外，Django 还提供了枚举类型，你可以通过将其子类化来简洁地定义选择：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.utils.translation</span> <span class="kn">import</span> <span class="n">gettext_lazy</span> <span class="k">as</span> <span class="n">_</span>

<span class="k">class</span> <span class="nc">Student</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>

    <span class="k">class</span> <span class="nc">YearInSchool</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">TextChoices</span><span class="p">):</span>
        <span class="n">FRESHMAN</span> <span class="o">=</span> <span class="s1">&#39;FR&#39;</span><span class="p">,</span> <span class="n">_</span><span class="p">(</span><span class="s1">&#39;Freshman&#39;</span><span class="p">)</span>
        <span class="n">SOPHOMORE</span> <span class="o">=</span> <span class="s1">&#39;SO&#39;</span><span class="p">,</span> <span class="n">_</span><span class="p">(</span><span class="s1">&#39;Sophomore&#39;</span><span class="p">)</span>
        <span class="n">JUNIOR</span> <span class="o">=</span> <span class="s1">&#39;JR&#39;</span><span class="p">,</span> <span class="n">_</span><span class="p">(</span><span class="s1">&#39;Junior&#39;</span><span class="p">)</span>
        <span class="n">SENIOR</span> <span class="o">=</span> <span class="s1">&#39;SR&#39;</span><span class="p">,</span> <span class="n">_</span><span class="p">(</span><span class="s1">&#39;Senior&#39;</span><span class="p">)</span>
        <span class="n">GRADUATE</span> <span class="o">=</span> <span class="s1">&#39;GR&#39;</span><span class="p">,</span> <span class="n">_</span><span class="p">(</span><span class="s1">&#39;Graduate&#39;</span><span class="p">)</span>

    <span class="n">year_in_school</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span>
        <span class="n">max_length</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span>
        <span class="n">choices</span><span class="o">=</span><span class="n">YearInSchool</span><span class="o">.</span><span class="n">choices</span><span class="p">,</span>
        <span class="n">default</span><span class="o">=</span><span class="n">YearInSchool</span><span class="o">.</span><span class="n">FRESHMAN</span><span class="p">,</span>
    <span class="p">)</span>

    <span class="k">def</span> <span class="nf">is_upperclass</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">year_in_school</span> <span class="ow">in</span> <span class="p">{</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">YearInSchool</span><span class="o">.</span><span class="n">JUNIOR</span><span class="p">,</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">YearInSchool</span><span class="o">.</span><span class="n">SENIOR</span><span class="p">,</span>
        <span class="p">}</span>
</pre></div>
</div>
<p>这些工作类似于 Python 标准库中的 <a class="reference external" href="https://docs.python.org/3/library/enum.html#module-enum" title="(在 Python v3.9)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">enum</span></code></a>，但是做了一些修改。</p>
<ul class="simple">
<li>枚举成员值是构造具体数据类型时要使用的参数元组。Django 支持在这个元组的末尾添加一个额外作为人可读的名称的字符串值 <code class="docutils literal notranslate"><span class="pre">label</span></code>。<code class="docutils literal notranslate"><span class="pre">label</span></code> 可以是一个惰性的可翻译字符串。因此，在大多数情况下，成员值将是一个 <code class="docutils literal notranslate"><span class="pre">(value,</span> <span class="pre">label)</span></code> 二元组。请看下面使用更复杂的数据类型 <a class="reference internal" href="#field-choices-enum-subclassing"><span class="std std-ref">子类化选择的例子</span></a>。如果没有提供元组，或者最后一项不是（惰性）字符串，<code class="docutils literal notranslate"><span class="pre">label</span></code> 是从成员名 <a class="reference internal" href="#field-choices-enum-auto-label"><span class="std std-ref">自动生成</span></a>。</li>
<li>在值上添加 <code class="docutils literal notranslate"><span class="pre">.label</span></code> 属性，以返回人类可读的名称。</li>
<li>在枚举类中添加了一些自定义属性—— <code class="docutils literal notranslate"><span class="pre">.choice</span></code>、<code class="docutils literal notranslate"><span class="pre">.labs</span></code>、<code class="docutils literal notranslate"><span class="pre">.values</span></code> 和 <code class="docutils literal notranslate"><span class="pre">.names</span></code> ——以便于访问枚举的这些单独部分的列表。在字段定义中，使用 <code class="docutils literal notranslate"><span class="pre">.choice</span></code> 作为一个合适的值传递给 <code class="xref py py-attr docutils literal notranslate"><span class="pre">choice</span></code>。</li>
<li>强制使用 <a class="reference external" href="https://docs.python.org/3/library/enum.html#enum.unique" title="(在 Python v3.9)"><code class="xref py py-func docutils literal notranslate"><span class="pre">enum.unique()</span></code></a> 是为了确保不能多次定义值。在选择一个字段时，不太可能会出现这种情况。</li>
</ul>
<p>请注意，使用 <code class="docutils literal notranslate"><span class="pre">YearInSchool.SENIOR</span></code>、<code class="docutils literal notranslate"><span class="pre">YearInSchool['SENIOR']</span></code> 或 <code class="docutils literal notranslate"><span class="pre">YearInSchool('SR')</span></code> 来访问或查找枚举成员，与成员上的 <code class="docutils literal notranslate"><span class="pre">.name</span></code> 和 <code class="docutils literal notranslate"><span class="pre">.value</span></code> 属性一样，都能正常工作。</p>
<p id="field-choices-enum-auto-label">如果你不需要翻译成人名，你可以从成员名称中推断出这些名称（用空格代替下划线并使用标题大小写）：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Vehicle</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">TextChoices</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">CAR</span> <span class="o">=</span> <span class="s1">&#39;C&#39;</span>
<span class="gp">... </span>    <span class="n">TRUCK</span> <span class="o">=</span> <span class="s1">&#39;T&#39;</span>
<span class="gp">... </span>    <span class="n">JET_SKI</span> <span class="o">=</span> <span class="s1">&#39;J&#39;</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Vehicle</span><span class="o">.</span><span class="n">JET_SKI</span><span class="o">.</span><span class="n">label</span>
<span class="go">&#39;Jet Ski&#39;</span>
</pre></div>
</div>
<p>由于枚举值需要为整数的情况极为常见，Django 提供了一个 <code class="docutils literal notranslate"><span class="pre">IntegerChoices</span></code> 类。例如：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Card</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>

    <span class="k">class</span> <span class="nc">Suit</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">IntegerChoices</span><span class="p">):</span>
        <span class="n">DIAMOND</span> <span class="o">=</span> <span class="mi">1</span>
        <span class="n">SPADE</span> <span class="o">=</span> <span class="mi">2</span>
        <span class="n">HEART</span> <span class="o">=</span> <span class="mi">3</span>
        <span class="n">CLUB</span> <span class="o">=</span> <span class="mi">4</span>

    <span class="n">suit</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">IntegerField</span><span class="p">(</span><span class="n">choices</span><span class="o">=</span><span class="n">Suit</span><span class="o">.</span><span class="n">choices</span><span class="p">)</span>
</pre></div>
</div>
<p>也可以使用 <a class="reference external" href="https://docs.python.org/3/library/enum.html#functional-api">Enum Functional API</a> ，但需要注意的是，标签是自动生成的，如上文所强调的：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">MedalType</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">TextChoices</span><span class="p">(</span><span class="s1">&#39;MedalType&#39;</span><span class="p">,</span> <span class="s1">&#39;GOLD SILVER BRONZE&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">MedalType</span><span class="o">.</span><span class="n">choices</span>
<span class="go">[(&#39;GOLD&#39;, &#39;Gold&#39;), (&#39;SILVER&#39;, &#39;Silver&#39;), (&#39;BRONZE&#39;, &#39;Bronze&#39;)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Place</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">IntegerChoices</span><span class="p">(</span><span class="s1">&#39;Place&#39;</span><span class="p">,</span> <span class="s1">&#39;FIRST SECOND THIRD&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Place</span><span class="o">.</span><span class="n">choices</span>
<span class="go">[(1, &#39;First&#39;), (2, &#39;Second&#39;), (3, &#39;Third&#39;)]</span>
</pre></div>
</div>
<p id="field-choices-enum-subclassing">如果你需要支持 <code class="docutils literal notranslate"><span class="pre">int</span></code> 或 <code class="docutils literal notranslate"><span class="pre">str</span></code> 以外的具体数据类型，你可以将 <code class="docutils literal notranslate"><span class="pre">Choices</span></code> 和所需的具体数据类型子类化，例如 <a class="reference external" href="https://docs.python.org/3/library/datetime.html#datetime.date" title="(在 Python v3.9)"><code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code></a> 与 <a class="reference internal" href="#django.db.models.DateField" title="django.db.models.DateField"><code class="xref py py-class docutils literal notranslate"><span class="pre">DateField</span></code></a> 一起使用：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">MoonLandings</span><span class="p">(</span><span class="n">datetime</span><span class="o">.</span><span class="n">date</span><span class="p">,</span> <span class="n">models</span><span class="o">.</span><span class="n">Choices</span><span class="p">):</span>
    <span class="n">APOLLO_11</span> <span class="o">=</span> <span class="mi">1969</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">20</span><span class="p">,</span> <span class="s1">&#39;Apollo 11 (Eagle)&#39;</span>
    <span class="n">APOLLO_12</span> <span class="o">=</span> <span class="mi">1969</span><span class="p">,</span> <span class="mi">11</span><span class="p">,</span> <span class="mi">19</span><span class="p">,</span> <span class="s1">&#39;Apollo 12 (Intrepid)&#39;</span>
    <span class="n">APOLLO_14</span> <span class="o">=</span> <span class="mi">1971</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="s1">&#39;Apollo 14 (Antares)&#39;</span>
    <span class="n">APOLLO_15</span> <span class="o">=</span> <span class="mi">1971</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">30</span><span class="p">,</span> <span class="s1">&#39;Apollo 15 (Falcon)&#39;</span>
    <span class="n">APOLLO_16</span> <span class="o">=</span> <span class="mi">1972</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">21</span><span class="p">,</span> <span class="s1">&#39;Apollo 16 (Orion)&#39;</span>
    <span class="n">APOLLO_17</span> <span class="o">=</span> <span class="mi">1972</span><span class="p">,</span> <span class="mi">12</span><span class="p">,</span> <span class="mi">11</span><span class="p">,</span> <span class="s1">&#39;Apollo 17 (Challenger)&#39;</span>
</pre></div>
</div>
<p>还有一些注意事项需要注意：</p>
<ul>
<li><p class="first">枚举类型不支持 <a class="reference internal" href="#field-choices-named-groups"><span class="std std-ref">命名组</span></a>。</p>
</li>
<li><p class="first">因为具有具体数据类型的枚举要求所有值都与类型相匹配，所以不能通过创建一个值为 <code class="docutils literal notranslate"><span class="pre">None</span></code> 的成员来覆盖 <a class="reference internal" href="#field-choices-blank-label"><span class="std std-ref">空白标签</span></a>。相反，在类上设置 <code class="docutils literal notranslate"><span class="pre">__empty__</span></code> 属性：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Answer</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">IntegerChoices</span><span class="p">):</span>
    <span class="n">NO</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="n">_</span><span class="p">(</span><span class="s1">&#39;No&#39;</span><span class="p">)</span>
    <span class="n">YES</span> <span class="o">=</span> <span class="mi">1</span><span class="p">,</span> <span class="n">_</span><span class="p">(</span><span class="s1">&#39;Yes&#39;</span><span class="p">)</span>

    <span class="n">__empty__</span> <span class="o">=</span> <span class="n">_</span><span class="p">(</span><span class="s1">&#39;(Unknown)&#39;</span><span class="p">)</span>
</pre></div>
</div>
</li>
</ul>
</div>
</div>
<div class="section" id="s-db-column">
<span id="db-column"></span><h3><code class="docutils literal notranslate"><span class="pre">db_column</span></code><a class="headerlink" href="#db-column" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.db.models.Field.db_column">
<code class="descclassname">Field.</code><code class="descname">db_column</code><a class="headerlink" href="#django.db.models.Field.db_column" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>这个字段要使用的数据库列名。如果没有给出列名，Django 将使用字段名。</p>
<p>如果你的数据库列名是 SQL 的保留字，或者包含了 Python 变量名中不允许的字符——特别是连字符——那也没关系。Django 会在幕后引用列名和表名。</p>
</div>
<div class="section" id="s-db-index">
<span id="db-index"></span><h3><code class="docutils literal notranslate"><span class="pre">db_index</span></code><a class="headerlink" href="#db-index" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.db.models.Field.db_index">
<code class="descclassname">Field.</code><code class="descname">db_index</code><a class="headerlink" href="#django.db.models.Field.db_index" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>如果是 <code class="docutils literal notranslate"><span class="pre">True</span></code>，将为该字段创建数据库索引。</p>
</div>
<div class="section" id="s-db-tablespace">
<span id="db-tablespace"></span><h3><code class="docutils literal notranslate"><span class="pre">db_tablespace</span></code><a class="headerlink" href="#db-tablespace" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.db.models.Field.db_tablespace">
<code class="descclassname">Field.</code><code class="descname">db_tablespace</code><a class="headerlink" href="#django.db.models.Field.db_tablespace" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>如果这个字段有索引，那么要为这个字段的索引使用的 <a class="reference internal" href="../../topics/db/tablespaces.html"><span class="doc">数据库表空间</span></a> 的名称。默认是项目的 <a class="reference internal" href="../settings.html#std:setting-DEFAULT_INDEX_TABLESPACE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">DEFAULT_INDEX_TABLESPACE</span></code></a> 设置（如果有设置），或者是模型的 <a class="reference internal" href="options.html#django.db.models.Options.db_tablespace" title="django.db.models.Options.db_tablespace"><code class="xref py py-attr docutils literal notranslate"><span class="pre">db_tablespace</span></code></a> （如果有）。如果后端不支持索引的表空间，则忽略此选项。</p>
</div>
<div class="section" id="s-default">
<span id="default"></span><h3><code class="docutils literal notranslate"><span class="pre">default</span></code><a class="headerlink" href="#default" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.db.models.Field.default">
<code class="descclassname">Field.</code><code class="descname">default</code><a class="headerlink" href="#django.db.models.Field.default" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>该字段的默认值。可以是一个值或者是个可调用的对象，如果是个可调用对象，每次实例化模型时都会调用该对象。</p>
<p>默认值不能是一个可更改的对象（模型实例、<code class="docutils literal notranslate"><span class="pre">list</span></code>、<code class="docutils literal notranslate"><span class="pre">set</span></code> 等），因为对该对象同一实例的引用将被用作所有新模型实例的缺省值。相反，将所需的默认值包裹在一个可调用对象中。例如，如果你想为 <a class="reference internal" href="#django.db.models.JSONField" title="django.db.models.JSONField"><code class="xref py py-class docutils literal notranslate"><span class="pre">JSONField</span></code></a> 指定一个默认的 <code class="docutils literal notranslate"><span class="pre">dict</span></code>，使用一个函数：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">contact_default</span><span class="p">():</span>
    <span class="k">return</span> <span class="p">{</span><span class="s2">&quot;email&quot;</span><span class="p">:</span> <span class="s2">&quot;to1@example.com&quot;</span><span class="p">}</span>

<span class="n">contact_info</span> <span class="o">=</span> <span class="n">JSONField</span><span class="p">(</span><span class="s2">&quot;ContactInfo&quot;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="n">contact_default</span><span class="p">)</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">lambda</span></code> 不能用于 <code class="docutils literal notranslate"><span class="pre">default</span></code> 等字段选项，因为它们不能被 <a class="reference internal" href="../../topics/migrations.html#migration-serializing"><span class="std std-ref">迁移序列化</span></a>。其他注意事项见该文档。</p>
<p>对于像 <a class="reference internal" href="#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a> 这样映射到模型实例的字段，默认应该是它们引用的字段的值（默认是 <code class="docutils literal notranslate"><span class="pre">pk</span></code> 除非 <a class="reference internal" href="#django.db.models.ForeignKey.to_field" title="django.db.models.ForeignKey.to_field"><code class="xref py py-attr docutils literal notranslate"><span class="pre">to_field</span></code></a> 被设置了），而不是模型实例。</p>
<p>当创建新的模型实例且没有为该字段提供值时，使用默认值。当字段是主键时，当字段设置为``None`` 时，也使用默认值。</p>
</div>
<div class="section" id="s-editable">
<span id="editable"></span><h3><code class="docutils literal notranslate"><span class="pre">editable</span></code><a class="headerlink" href="#editable" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.db.models.Field.editable">
<code class="descclassname">Field.</code><code class="descname">editable</code><a class="headerlink" href="#django.db.models.Field.editable" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>如果是 <code class="docutils literal notranslate"><span class="pre">False</span></code>，该字段将不会在管理或任何其他 <a class="reference internal" href="../../topics/forms/modelforms.html#django.forms.ModelForm" title="django.forms.ModelForm"><code class="xref py py-class docutils literal notranslate"><span class="pre">ModelForm</span></code></a> 中显示。在 <a class="reference internal" href="instances.html#validating-objects"><span class="std std-ref">模型验证</span></a> 中也会跳过。默认为 <code class="docutils literal notranslate"><span class="pre">True</span></code>。</p>
</div>
<div class="section" id="s-error-messages">
<span id="error-messages"></span><h3><code class="docutils literal notranslate"><span class="pre">error_messages</span></code><a class="headerlink" href="#error-messages" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.db.models.Field.error_messages">
<code class="descclassname">Field.</code><code class="descname">error_messages</code><a class="headerlink" href="#django.db.models.Field.error_messages" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p><code class="docutils literal notranslate"><span class="pre">error_messages</span></code> 参数可以让你覆盖该字段引发的默认消息。传入一个与你想覆盖的错误信息相匹配的键值的字典。</p>
<p>错误信息键包括 <code class="docutils literal notranslate"><span class="pre">null</span></code>、<code class="docutils literal notranslate"><span class="pre">blank</span></code>、<code class="docutils literal notranslate"><span class="pre">invalid</span></code>、<code class="docutils literal notranslate"><span class="pre">invalid_choice</span></code>、<code class="docutils literal notranslate"><span class="pre">unique</span></code> 和 <code class="docutils literal notranslate"><span class="pre">unique_for_date</span></code>。在下面的 <a class="reference internal" href="#field-types">字段类型</a> 一节中为每个字段指定了额外的错误信息键。</p>
<p>这些错误信息通常不会传播到表单中。参见 <a class="reference internal" href="../../topics/forms/modelforms.html#considerations-regarding-model-errormessages"><span class="std std-ref">Considerations regarding model's error_messages</span></a>。</p>
</div>
<div class="section" id="s-help-text">
<span id="help-text"></span><h3><code class="docutils literal notranslate"><span class="pre">help_text</span></code><a class="headerlink" href="#help-text" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.db.models.Field.help_text">
<code class="descclassname">Field.</code><code class="descname">help_text</code><a class="headerlink" href="#django.db.models.Field.help_text" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>额外的“帮助”文本，随表单控件一同显示。即便你的字段未用于表单，它对于生成文档也是很有用的。</p>
<p>请注意，在自动生成的表格中，这个值 <em>不是</em> HTML 转义的。如果你愿意的话，你可以在 <a class="reference internal" href="#django.db.models.Field.help_text" title="django.db.models.Field.help_text"><code class="xref py py-attr docutils literal notranslate"><span class="pre">help_text</span></code></a> 中加入 HTML。例如：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">help_text</span><span class="o">=</span><span class="s2">&quot;Please use the following format: &lt;em&gt;YYYY-MM-DD&lt;/em&gt;.&quot;</span>
</pre></div>
</div>
<p>或者你可以使用纯文本和 <a class="reference internal" href="../utils.html#django.utils.html.escape" title="django.utils.html.escape"><code class="xref py py-func docutils literal notranslate"><span class="pre">django.utils.html.escape()</span></code></a> 来转义任何 HTML 特殊字符。确保你转义任何可能来自不受信任的用户的帮助文本，以避免跨站脚本攻击。</p>
</div>
<div class="section" id="s-primary-key">
<span id="primary-key"></span><h3><code class="docutils literal notranslate"><span class="pre">primary_key</span></code><a class="headerlink" href="#primary-key" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.db.models.Field.primary_key">
<code class="descclassname">Field.</code><code class="descname">primary_key</code><a class="headerlink" href="#django.db.models.Field.primary_key" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>如果设置为 <code class="docutils literal notranslate"><span class="pre">True</span></code> ，将该字段设置为该模型的主键。</p>
<p>如果你没有为模型中的任何字段指定 <code class="docutils literal notranslate"><span class="pre">primary_key=True</span></code>，Django 会自动添加一个字段来保存主键，所以你不需要在任何字段上设置 <cite>primary_key=True</cite>，除非你想覆盖默认主键行为。自动创建的主键字段的类型可以在 <a class="reference internal" href="../applications.html#django.apps.AppConfig.default_auto_field" title="django.apps.AppConfig.default_auto_field"><code class="xref py py-attr docutils literal notranslate"><span class="pre">AppConfig.default_auto_field</span></code></a> 中为每个应用程序指定，或者在 <a class="reference internal" href="../settings.html#std:setting-DEFAULT_AUTO_FIELD"><code class="xref std std-setting docutils literal notranslate"><span class="pre">DEFAULT_AUTO_FIELD</span></code></a> 配置中全局指定。更多信息，请参阅 <a class="reference internal" href="../../topics/db/models.html#automatic-primary-key-fields"><span class="std std-ref">Automatic primary key fields</span></a>。</p>
<p><code class="docutils literal notranslate"><span class="pre">primary_key=True</span></code> 意味着 <a class="reference internal" href="#django.db.models.Field.null" title="django.db.models.Field.null"><code class="xref py py-attr docutils literal notranslate"><span class="pre">null=False</span></code></a> 和 <a class="reference internal" href="#django.db.models.Field.unique" title="django.db.models.Field.unique"><code class="xref py py-attr docutils literal notranslate"><span class="pre">unique=True</span></code></a>。一个对象只允许有一个主键。</p>
<p>主键字段是只读的。如果您改变了现有对象的主键值，然后将其保存，则会在旧对象旁边创建一个新对象。</p>
<div class="versionchanged">
<span class="title">Changed in Django 3.2:</span> <p>在旧版本中，自动创建的主键字段总是 <a class="reference internal" href="#django.db.models.AutoField" title="django.db.models.AutoField"><code class="xref py py-class docutils literal notranslate"><span class="pre">AutoField</span></code></a>。</p>
</div>
</div>
<div class="section" id="s-unique">
<span id="unique"></span><h3><code class="docutils literal notranslate"><span class="pre">unique</span></code><a class="headerlink" href="#unique" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.db.models.Field.unique">
<code class="descclassname">Field.</code><code class="descname">unique</code><a class="headerlink" href="#django.db.models.Field.unique" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>如果设置为 <code class="docutils literal notranslate"><span class="pre">True</span></code>，这个字段必须在整个表中保持值唯一。</p>
<p>这是在数据库级别和模型验证中强制执行的。如果你试图保存一个在 <a class="reference internal" href="#django.db.models.Field.unique" title="django.db.models.Field.unique"><code class="xref py py-attr docutils literal notranslate"><span class="pre">unique</span></code></a> 字段中存在重复值的模型，模型的 <a class="reference internal" href="instances.html#django.db.models.Model.save" title="django.db.models.Model.save"><code class="xref py py-meth docutils literal notranslate"><span class="pre">save()</span></code></a> 方法将引发 <a class="reference internal" href="../exceptions.html#django.db.IntegrityError" title="django.db.IntegrityError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">django.db.IntegrityError</span></code></a>。</p>
<p>除了 <a class="reference internal" href="#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><code class="xref py py-class docutils literal notranslate"><span class="pre">ManyToManyField</span></code></a> 和 <a class="reference internal" href="#django.db.models.OneToOneField" title="django.db.models.OneToOneField"><code class="xref py py-class docutils literal notranslate"><span class="pre">OneToOneField</span></code></a> 之外，该选项对所有字段类型有效。</p>
<p>请注意，当 <code class="docutils literal notranslate"><span class="pre">unique</span></code> 为 <code class="docutils literal notranslate"><span class="pre">True</span></code> 时，你不需要指定 <a class="reference internal" href="#django.db.models.Field.db_index" title="django.db.models.Field.db_index"><code class="xref py py-attr docutils literal notranslate"><span class="pre">db_index</span></code></a>，因为 <code class="docutils literal notranslate"><span class="pre">unique</span></code> 意味着创建一个索引。</p>
</div>
<div class="section" id="s-unique-for-date">
<span id="unique-for-date"></span><h3><code class="docutils literal notranslate"><span class="pre">unique_for_date</span></code><a class="headerlink" href="#unique-for-date" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.db.models.Field.unique_for_date">
<code class="descclassname">Field.</code><code class="descname">unique_for_date</code><a class="headerlink" href="#django.db.models.Field.unique_for_date" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>将其设置为 <a class="reference internal" href="#django.db.models.DateField" title="django.db.models.DateField"><code class="xref py py-class docutils literal notranslate"><span class="pre">DateField</span></code></a> 或 <a class="reference internal" href="#django.db.models.DateTimeField" title="django.db.models.DateTimeField"><code class="xref py py-class docutils literal notranslate"><span class="pre">DateTimeField</span></code></a> 的名称，要求该字段的日期字段值是唯一的。</p>
<p>例如，如果你的字段 <code class="docutils literal notranslate"><span class="pre">title</span></code> 有 <code class="docutils literal notranslate"><span class="pre">unique_for_date=&quot;pub_date&quot;</span></code>，那么 Django 就不允许输入两条相同 <code class="docutils literal notranslate"><span class="pre">title</span></code> 和 <code class="docutils literal notranslate"><span class="pre">pub_date</span></code> 的记录。</p>
<p>请注意，如果将其设置为指向 <a class="reference internal" href="#django.db.models.DateTimeField" title="django.db.models.DateTimeField"><code class="xref py py-class docutils literal notranslate"><span class="pre">DateTimeField</span></code></a>，则只考虑该字段的日期部分。此外，当 <a class="reference internal" href="../settings.html#std:setting-USE_TZ"><code class="xref std std-setting docutils literal notranslate"><span class="pre">USE_TZ</span></code></a> 为 <code class="docutils literal notranslate"><span class="pre">True</span></code> 时，检查将在对象保存时的 <a class="reference internal" href="../../topics/i18n/timezones.html#default-current-time-zone"><span class="std std-ref">当前时区</span></a> 中进行。</p>
<p>这在模型验证过程中由 <a class="reference internal" href="instances.html#django.db.models.Model.validate_unique" title="django.db.models.Model.validate_unique"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Model.validate_unique()</span></code></a> 强制执行，但在数据库级别上不执行。如果任何 <a class="reference internal" href="#django.db.models.Field.unique_for_date" title="django.db.models.Field.unique_for_date"><code class="xref py py-attr docutils literal notranslate"><span class="pre">unique_for_date</span></code></a> 约束涉及的字段不属于 <a class="reference internal" href="../../topics/forms/modelforms.html#django.forms.ModelForm" title="django.forms.ModelForm"><code class="xref py py-class docutils literal notranslate"><span class="pre">ModelForm</span></code></a> （例如，如果其中一个字段被列在``exclude``中，或者有 <a class="reference internal" href="#django.db.models.Field.editable" title="django.db.models.Field.editable"><code class="xref py py-attr docutils literal notranslate"><span class="pre">editable=False</span></code></a> ）， <a class="reference internal" href="instances.html#django.db.models.Model.validate_unique" title="django.db.models.Model.validate_unique"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Model.validate_unique()</span></code></a> 将跳过对该特定约束的验证。</p>
</div>
<div class="section" id="s-unique-for-month">
<span id="unique-for-month"></span><h3><code class="docutils literal notranslate"><span class="pre">unique_for_month</span></code><a class="headerlink" href="#unique-for-month" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.db.models.Field.unique_for_month">
<code class="descclassname">Field.</code><code class="descname">unique_for_month</code><a class="headerlink" href="#django.db.models.Field.unique_for_month" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>像 <a class="reference internal" href="#django.db.models.Field.unique_for_date" title="django.db.models.Field.unique_for_date"><code class="xref py py-attr docutils literal notranslate"><span class="pre">unique_for_date</span></code></a> 一样，但要求字段对月份是唯一的。</p>
</div>
<div class="section" id="s-unique-for-year">
<span id="unique-for-year"></span><h3><code class="docutils literal notranslate"><span class="pre">unique_for_year</span></code><a class="headerlink" href="#unique-for-year" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.db.models.Field.unique_for_year">
<code class="descclassname">Field.</code><code class="descname">unique_for_year</code><a class="headerlink" href="#django.db.models.Field.unique_for_year" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>如 <code class="xref py py-attr docutils literal notranslate"><span class="pre">unique_fordate</span></code> 和 <code class="xref py py-attr docutils literal notranslate"><span class="pre">unique_formonth</span></code>。</p>
</div>
<div class="section" id="s-verbose-name">
<span id="verbose-name"></span><h3><code class="docutils literal notranslate"><span class="pre">verbose_name</span></code><a class="headerlink" href="#verbose-name" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.db.models.Field.verbose_name">
<code class="descclassname">Field.</code><code class="descname">verbose_name</code><a class="headerlink" href="#django.db.models.Field.verbose_name" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>字段的一个人类可读名称，如果没有给定详细名称，Django 会使用字段的属性名自动创建，并将下划线转换为空格。参见 <a class="reference internal" href="../../topics/db/models.html#verbose-field-names"><span class="std std-ref">详细字段名</span></a>。</p>
</div>
<div class="section" id="s-validators">
<span id="validators"></span><h3><code class="docutils literal notranslate"><span class="pre">validators</span></code><a class="headerlink" href="#validators" title="永久链接至标题">¶</a></h3>
<dl class="attribute">
<dt id="django.db.models.Field.validators">
<code class="descclassname">Field.</code><code class="descname">validators</code><a class="headerlink" href="#django.db.models.Field.validators" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>要为该字段运行的验证器列表。更多信息请参见 <a class="reference internal" href="../validators.html"><span class="doc">验证器文档</span></a>。</p>
<div class="section" id="s-registering-and-fetching-lookups">
<span id="registering-and-fetching-lookups"></span><h4>注册和获取查询<a class="headerlink" href="#registering-and-fetching-lookups" title="永久链接至标题">¶</a></h4>
<p><code class="docutils literal notranslate"><span class="pre">Field</span></code> 实现了 <a class="reference internal" href="lookups.html#lookup-registration-api"><span class="std std-ref">查询注册 API</span></a>。该 API 可用于自定义字段类的哪些查询是可用的，以及如何从字段中获取查询。</p>
</div>
</div>
</div>
<div class="section" id="s-field-types">
<span id="s-model-field-types"></span><span id="field-types"></span><span id="model-field-types"></span><h2>字段类型<a class="headerlink" href="#field-types" title="永久链接至标题">¶</a></h2>
<div class="section" id="s-autofield">
<span id="autofield"></span><h3><code class="docutils literal notranslate"><span class="pre">AutoField</span></code><a class="headerlink" href="#autofield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.db.models.AutoField">
<em class="property">class </em><code class="descname">AutoField</code>(<em>**options</em>)<a class="headerlink" href="#django.db.models.AutoField" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>一个 <a class="reference internal" href="#django.db.models.IntegerField" title="django.db.models.IntegerField"><code class="xref py py-class docutils literal notranslate"><span class="pre">IntegerField</span></code></a>，根据可用的 ID 自动递增。你通常不需要直接使用它；如果你没有指定，主键字段会自动添加到你的模型中。参见 <a class="reference internal" href="../../topics/db/models.html#automatic-primary-key-fields"><span class="std std-ref">Automatic primary key fields</span></a>。</p>
</div>
<div class="section" id="s-bigautofield">
<span id="bigautofield"></span><h3><code class="docutils literal notranslate"><span class="pre">BigAutoField</span></code><a class="headerlink" href="#bigautofield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.db.models.BigAutoField">
<em class="property">class </em><code class="descname">BigAutoField</code>(<em>**options</em>)<a class="headerlink" href="#django.db.models.BigAutoField" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>一个 64 位整数，与 <a class="reference internal" href="#django.db.models.AutoField" title="django.db.models.AutoField"><code class="xref py py-class docutils literal notranslate"><span class="pre">AutoField</span></code></a> 很相似，但保证适合 <code class="docutils literal notranslate"><span class="pre">1</span></code> 到 <code class="docutils literal notranslate"><span class="pre">9223372036854775807</span></code> 的数字。</p>
</div>
<div class="section" id="s-bigintegerfield">
<span id="bigintegerfield"></span><h3><code class="docutils literal notranslate"><span class="pre">BigIntegerField</span></code><a class="headerlink" href="#bigintegerfield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.db.models.BigIntegerField">
<em class="property">class </em><code class="descname">BigIntegerField</code>(<em>**options</em>)<a class="headerlink" href="#django.db.models.BigIntegerField" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>一个 64 位的整数，和 <a class="reference internal" href="#django.db.models.IntegerField" title="django.db.models.IntegerField"><code class="xref py py-class docutils literal notranslate"><span class="pre">IntegerField</span></code></a> 很像，只是它保证适合从 <code class="docutils literal notranslate"><span class="pre">-9223372036854775808</span></code> 到 <code class="docutils literal notranslate"><span class="pre">9223372036854775807</span></code> 的数字。该字段的默认表单部件是一个 <a class="reference internal" href="../forms/widgets.html#django.forms.NumberInput" title="django.forms.NumberInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">NumberInput</span></code></a>。</p>
</div>
<div class="section" id="s-binaryfield">
<span id="binaryfield"></span><h3><code class="docutils literal notranslate"><span class="pre">BinaryField</span></code><a class="headerlink" href="#binaryfield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.db.models.BinaryField">
<em class="property">class </em><code class="descname">BinaryField</code>(<em>max_length=None</em>, <em>**options</em>)<a class="headerlink" href="#django.db.models.BinaryField" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>一个用于存储原始二进制数据的字段。可以指定为 <a class="reference external" href="https://docs.python.org/3/library/stdtypes.html#bytes" title="(在 Python v3.9)"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a>、<a class="reference external" href="https://docs.python.org/3/library/stdtypes.html#bytearray" title="(在 Python v3.9)"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a> 或 <a class="reference external" href="https://docs.python.org/3/library/stdtypes.html#memoryview" title="(在 Python v3.9)"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a>。</p>
<p>默认情况下，<code class="docutils literal notranslate"><span class="pre">BinaryField</span></code> 将 <code class="xref py py-attr docutils literal notranslate"><span class="pre">ediditable`</span></code> 设置为 <code class="docutils literal notranslate"><span class="pre">False</span></code>，在这种情况下，它不能被包含在 <a class="reference internal" href="../../topics/forms/modelforms.html#django.forms.ModelForm" title="django.forms.ModelForm"><code class="xref py py-class docutils literal notranslate"><span class="pre">ModelForm</span></code></a> 中。</p>
<p><code class="docutils literal notranslate"><span class="pre">BinaryField</span></code> 有一个额外的可选参数：</p>
<dl class="attribute">
<dt id="django.db.models.BinaryField.max_length">
<code class="descclassname">BinaryField.</code><code class="descname">max_length</code><a class="headerlink" href="#django.db.models.BinaryField.max_length" title="永久链接至目标">¶</a></dt>
<dd><p>字段的最大长度（以字符为单位）。最大长度在 Django 的验证中使用 <a class="reference internal" href="../validators.html#django.core.validators.MaxLengthValidator" title="django.core.validators.MaxLengthValidator"><code class="xref py py-class docutils literal notranslate"><span class="pre">MaxLengthValidator</span></code></a> 强制执行。</p>
</dd></dl>

<div class="admonition-abusing-binaryfield admonition">
<p class="first admonition-title">滥用 <code class="docutils literal notranslate"><span class="pre">BinaryField</span></code></p>
<p class="last">虽然你可能会想到在数据库中存储文件，但考虑到这在99%的情况下是糟糕的设计。这个字段 <em>不能</em> 代替正确的 <a class="reference internal" href="../../howto/static-files/index.html"><span class="doc">静态文件</span></a> 处理。</p>
</div>
</div>
<div class="section" id="s-booleanfield">
<span id="booleanfield"></span><h3><code class="docutils literal notranslate"><span class="pre">BooleanField</span></code><a class="headerlink" href="#booleanfield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.db.models.BooleanField">
<em class="property">class </em><code class="descname">BooleanField</code>(<em>**options</em>)<a class="headerlink" href="#django.db.models.BooleanField" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>一个 true／false 字段。</p>
<p>该字段的默认表单部件是 <a class="reference internal" href="../forms/widgets.html#django.forms.CheckboxInput" title="django.forms.CheckboxInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">CheckboxInput</span></code></a>，或者如果 <a class="reference internal" href="#django.db.models.Field.null" title="django.db.models.Field.null"><code class="xref py py-attr docutils literal notranslate"><span class="pre">null=True</span></code></a> 则是 <a class="reference internal" href="../forms/widgets.html#django.forms.NullBooleanSelect" title="django.forms.NullBooleanSelect"><code class="xref py py-class docutils literal notranslate"><span class="pre">NullBooleanSelect</span></code></a>。</p>
<p>当 <a class="reference internal" href="#django.db.models.Field.default" title="django.db.models.Field.default"><code class="xref py py-attr docutils literal notranslate"><span class="pre">Field.default</span></code></a> 没有定义时，<code class="docutils literal notranslate"><span class="pre">BooleanField</span></code> 的默认值是 <code class="docutils literal notranslate"><span class="pre">None</span></code>。</p>
</div>
<div class="section" id="s-charfield">
<span id="charfield"></span><h3><code class="docutils literal notranslate"><span class="pre">CharField</span></code><a class="headerlink" href="#charfield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.db.models.CharField">
<em class="property">class </em><code class="descname">CharField</code>(<em>max_length=None</em>, <em>**options</em>)<a class="headerlink" href="#django.db.models.CharField" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>一个字符串字段，适用于小到大的字符串。</p>
<p>对于大量的文本，使用 <a class="reference internal" href="#django.db.models.TextField" title="django.db.models.TextField"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextField</span></code></a>。</p>
<p>该字段的默认表单部件是一个 <a class="reference internal" href="../forms/widgets.html#django.forms.TextInput" title="django.forms.TextInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextInput</span></code></a>。</p>
<p><a class="reference internal" href="#django.db.models.CharField" title="django.db.models.CharField"><code class="xref py py-class docutils literal notranslate"><span class="pre">CharField</span></code></a> 有两个额外的参数：</p>
<dl class="attribute">
<dt id="django.db.models.CharField.max_length">
<code class="descclassname">CharField.</code><code class="descname">max_length</code><a class="headerlink" href="#django.db.models.CharField.max_length" title="永久链接至目标">¶</a></dt>
<dd><p>必须的。该字段的最大长度（以字符为单位）。max_length 在数据库层面强制执行，在 Django 的验证中使用 <a class="reference internal" href="../validators.html#django.core.validators.MaxLengthValidator" title="django.core.validators.MaxLengthValidator"><code class="xref py py-class docutils literal notranslate"><span class="pre">MaxLengthValidator</span></code></a>。</p>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">如果你编写的应用程序必须可移植到多个数据库后端，你应该意识到，有些后端对 <code class="docutils literal notranslate"><span class="pre">max_length</span></code> 有限制。详情请参考 <a class="reference internal" href="../databases.html"><span class="doc">数据库后端注释</span></a>。</p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="django.db.models.CharField.db_collation">
<code class="descclassname">CharField.</code><code class="descname">db_collation</code><a class="headerlink" href="#django.db.models.CharField.db_collation" title="永久链接至目标">¶</a></dt>
<dd><div class="versionadded">
<span class="title">New in Django 3.2.</span> </div>
<p>可选的。该字段的数据库字符序名称。</p>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">字符序名称是不标准化的。因此，这将无法在多个数据库后端之间进行移植。</p>
</div>
<div class="admonition-oracle admonition">
<p class="first admonition-title">Oracle</p>
<p class="last">Oracle 只有在 <code class="docutils literal notranslate"><span class="pre">MAX_STRING_SIZE</span></code> 数据库初始化参数被设置为 <code class="docutils literal notranslate"><span class="pre">EXTENDED</span></code> 时，才支持字符序。</p>
</div>
</dd></dl>

</div>
<div class="section" id="s-datefield">
<span id="datefield"></span><h3><code class="docutils literal notranslate"><span class="pre">DateField</span></code><a class="headerlink" href="#datefield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.db.models.DateField">
<em class="property">class </em><code class="descname">DateField</code>(<em>auto_now=False</em>, <em>auto_now_add=False</em>, <em>**options</em>)<a class="headerlink" href="#django.db.models.DateField" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>一个日期，在 Python 中用一个 <code class="docutils literal notranslate"><span class="pre">datetime.date</span></code> 实例表示。有一些额外的、可选的参数。</p>
<dl class="attribute">
<dt id="django.db.models.DateField.auto_now">
<code class="descclassname">DateField.</code><code class="descname">auto_now</code><a class="headerlink" href="#django.db.models.DateField.auto_now" title="永久链接至目标">¶</a></dt>
<dd><p>每次保存对象时，自动将该字段设置为现在。对于“最后修改”的时间戳很有用。请注意，当前日期 <em>总是</em> 被使用，而不仅仅是一个你可以覆盖的默认值。</p>
<p>只有在调用 <a class="reference internal" href="instances.html#django.db.models.Model.save" title="django.db.models.Model.save"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Model.save()</span></code></a> 时，该字段才会自动更新。当以其他方式对其他字段进行更新时，如 <a class="reference internal" href="querysets.html#django.db.models.query.QuerySet.update" title="django.db.models.query.QuerySet.update"><code class="xref py py-meth docutils literal notranslate"><span class="pre">QuerySet.update()</span></code></a>，该字段不会被更新，尽管你可以在这样的更新中为该字段指定一个自定义值。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.db.models.DateField.auto_now_add">
<code class="descclassname">DateField.</code><code class="descname">auto_now_add</code><a class="headerlink" href="#django.db.models.DateField.auto_now_add" title="永久链接至目标">¶</a></dt>
<dd><p>当第一次创建对象时，自动将该字段设置为现在。对创建时间戳很有用。请注意，当前日期是 <em>始终</em> 使用的；它不是一个你可以覆盖的默认值。因此，即使你在创建对象时为该字段设置了一个值，它也会被忽略。如果你想修改这个字段，可以设置以下内容来代替 <code class="docutils literal notranslate"><span class="pre">auto_now_add=True</span></code> ：</p>
<ul class="simple">
<li>对于 <a class="reference internal" href="#django.db.models.DateField" title="django.db.models.DateField"><code class="xref py py-class docutils literal notranslate"><span class="pre">DateField</span></code></a>: <code class="docutils literal notranslate"><span class="pre">default=date.today</span></code> ——来自 <a class="reference external" href="https://docs.python.org/3/library/datetime.html#datetime.date.today" title="(在 Python v3.9)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">datetime.date.today()</span></code></a></li>
<li>对于 <a class="reference internal" href="#django.db.models.DateTimeField" title="django.db.models.DateTimeField"><code class="xref py py-class docutils literal notranslate"><span class="pre">DateTimeField</span></code></a>: <code class="docutils literal notranslate"><span class="pre">default=timezone.now</span></code> ——来自 <a class="reference internal" href="../utils.html#django.utils.timezone.now" title="django.utils.timezone.now"><code class="xref py py-func docutils literal notranslate"><span class="pre">django.utils.timezone.now()</span></code></a></li>
</ul>
</dd></dl>

<p>该字段的默认表单部件是一个 <a class="reference internal" href="../forms/widgets.html#django.forms.DateInput" title="django.forms.DateInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">DateInput</span></code></a>。管理中增加了一个 JavaScript 日历，以及“今天”的快捷方式。包含一个额外的 <code class="docutils literal notranslate"><span class="pre">invalid_date</span></code> 错误信息键。</p>
<p><code class="docutils literal notranslate"><span class="pre">auto_now_add</span></code>、<code class="docutils literal notranslate"><span class="pre">auto_now</span></code> 和 <code class="docutils literal notranslate"><span class="pre">default</span></code> 选项是相互排斥的。这些选项的任何组合都会导致错误。</p>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">目前，将 <code class="docutils literal notranslate"><span class="pre">auto_now</span></code> 或 <code class="docutils literal notranslate"><span class="pre">auto_now_add</span></code> 设置为 <code class="docutils literal notranslate"><span class="pre">True</span></code>，将导致该字段设置为 <code class="docutils literal notranslate"><span class="pre">editable=False</span></code> 和 <code class="docutils literal notranslate"><span class="pre">blank=True</span></code>。</p>
</div>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last"><code class="docutils literal notranslate"><span class="pre">auto_now</span></code> 和 <code class="docutils literal notranslate"><span class="pre">auto_now_add</span></code> 选项将始终使用创建或更新时 <a class="reference internal" href="../../topics/i18n/timezones.html#default-current-time-zone"><span class="std std-ref">默认时区</span></a> 的日期。如果你需要一些不同的东西，你可能需要考虑使用你自己的可调用的默认值，或者覆盖 <code class="docutils literal notranslate"><span class="pre">save()</span></code> 而不是使用 <code class="docutils literal notranslate"><span class="pre">auto_now</span></code> 或 <code class="docutils literal notranslate"><span class="pre">auto_now_add</span></code> ；或者使用 <code class="docutils literal notranslate"><span class="pre">DateTimeField</span></code> 而不是 <code class="docutils literal notranslate"><span class="pre">DateField</span></code>，并决定如何在显示时间处理从日期时间到日期的转换。</p>
</div>
</div>
<div class="section" id="s-datetimefield">
<span id="datetimefield"></span><h3><code class="docutils literal notranslate"><span class="pre">DateTimeField</span></code><a class="headerlink" href="#datetimefield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.db.models.DateTimeField">
<em class="property">class </em><code class="descname">DateTimeField</code>(<em>auto_now=False</em>, <em>auto_now_add=False</em>, <em>**options</em>)<a class="headerlink" href="#django.db.models.DateTimeField" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>一个日期和时间，在 Python 中用一个 <code class="docutils literal notranslate"><span class="pre">datetime.datetime</span></code> 实例表示。与 <a class="reference internal" href="#django.db.models.DateField" title="django.db.models.DateField"><code class="xref py py-class docutils literal notranslate"><span class="pre">DateField</span></code></a> 一样，使用相同的额外参数。</p>
<p>该字段的默认表单部件是一个单独的 <a class="reference internal" href="../forms/widgets.html#django.forms.DateTimeInput" title="django.forms.DateTimeInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">DateTimeInput</span></code></a>。管理中使用两个单独的 <a class="reference internal" href="../forms/widgets.html#django.forms.TextInput" title="django.forms.TextInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextInput</span></code></a> 部件，并使用 JavaScript 快捷方式。</p>
</div>
<div class="section" id="s-decimalfield">
<span id="decimalfield"></span><h3><code class="docutils literal notranslate"><span class="pre">DecimalField</span></code><a class="headerlink" href="#decimalfield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.db.models.DecimalField">
<em class="property">class </em><code class="descname">DecimalField</code>(<em>max_digits=None</em>, <em>decimal_places=None</em>, <em>**options</em>)<a class="headerlink" href="#django.db.models.DecimalField" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>一个固定精度的十进制数，在 Python 中用一个 <a class="reference external" href="https://docs.python.org/3/library/decimal.html#decimal.Decimal" title="(在 Python v3.9)"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> 实例来表示。它使用 <a class="reference internal" href="../validators.html#django.core.validators.DecimalValidator" title="django.core.validators.DecimalValidator"><code class="xref py py-class docutils literal notranslate"><span class="pre">DecimalValidator</span></code></a> 验证输入。</p>
<p>有两个 <strong>必要的</strong> 参数：</p>
<dl class="attribute">
<dt id="django.db.models.DecimalField.max_digits">
<code class="descclassname">DecimalField.</code><code class="descname">max_digits</code><a class="headerlink" href="#django.db.models.DecimalField.max_digits" title="永久链接至目标">¶</a></dt>
<dd><p>数字中允许的最大位数。请注意，这个数字必须大于或等于 <code class="docutils literal notranslate"><span class="pre">decimal_places</span></code>。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.db.models.DecimalField.decimal_places">
<code class="descclassname">DecimalField.</code><code class="descname">decimal_places</code><a class="headerlink" href="#django.db.models.DecimalField.decimal_places" title="永久链接至目标">¶</a></dt>
<dd><p>与数字一起存储的小数位数。</p>
</dd></dl>

<p>例如，如果要存储精度为小数点后两位的 <code class="docutils literal notranslate"><span class="pre">999</span></code> 的数字，你可以使用：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">models</span><span class="o">.</span><span class="n">DecimalField</span><span class="p">(</span><span class="o">...</span><span class="p">,</span> <span class="n">max_digits</span><span class="o">=</span><span class="mi">5</span><span class="p">,</span> <span class="n">decimal_places</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
</pre></div>
</div>
<p>并以 10 位小数的精度来存储最多约 10 亿的数字：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">models</span><span class="o">.</span><span class="n">DecimalField</span><span class="p">(</span><span class="o">...</span><span class="p">,</span> <span class="n">max_digits</span><span class="o">=</span><span class="mi">19</span><span class="p">,</span> <span class="n">decimal_places</span><span class="o">=</span><span class="mi">10</span><span class="p">)</span>
</pre></div>
</div>
<p>当 <a class="reference internal" href="../forms/fields.html#django.forms.Field.localize" title="django.forms.Field.localize"><code class="xref py py-attr docutils literal notranslate"><span class="pre">localize</span></code></a> 为 <code class="docutils literal notranslate"><span class="pre">False</span></code> 时是 <a class="reference internal" href="../forms/widgets.html#django.forms.NumberInput" title="django.forms.NumberInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">NumberInput</span></code></a> 否则，该字段的默认表单部件是 <a class="reference internal" href="../forms/widgets.html#django.forms.TextInput" title="django.forms.TextInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextInput</span></code></a>。</p>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">关于 <a class="reference internal" href="#django.db.models.FloatField" title="django.db.models.FloatField"><code class="xref py py-class docutils literal notranslate"><span class="pre">FloatField</span></code></a> 和 <a class="reference internal" href="#django.db.models.DecimalField" title="django.db.models.DecimalField"><code class="xref py py-class docutils literal notranslate"><span class="pre">DecimalField</span></code></a> 类之间差异的更多信息，请参见 <a class="reference internal" href="#floatfield-vs-decimalfield"><span class="std std-ref">FloatField vs. DecimalField</span></a>。你还应该注意小数字段的 <a class="reference internal" href="../databases.html#sqlite-decimal-handling"><span class="std std-ref">SQLite 限制</span></a>。</p>
</div>
</div>
<div class="section" id="s-durationfield">
<span id="durationfield"></span><h3><code class="docutils literal notranslate"><span class="pre">DurationField</span></code><a class="headerlink" href="#durationfield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.db.models.DurationField">
<em class="property">class </em><code class="descname">DurationField</code>(<em>**options</em>)<a class="headerlink" href="#django.db.models.DurationField" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>一个用于存储时间段的字段——在 Python 中用 <a class="reference external" href="https://docs.python.org/3/library/datetime.html#datetime.timedelta" title="(在 Python v3.9)"><code class="xref py py-class docutils literal notranslate"><span class="pre">timedelta</span></code></a> 建模。当在 PostgreSQL 上使用时，使用的数据类型是 <code class="docutils literal notranslate"><span class="pre">interval</span></code>，在 Oracle 上使用的数据类型是 <code class="docutils literal notranslate"><span class="pre">INTERVAL</span> <span class="pre">DAY(9)</span> <span class="pre">TO</span> <span class="pre">SECOND(6)</span></code>。否则使用微秒的 <code class="docutils literal notranslate"><span class="pre">bigint</span></code>。</p>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last"><code class="docutils literal notranslate"><span class="pre">DurationField</span></code> 的算术在大多数情况下是可行的。但在 PostgreSQL 以外的所有数据库中，将 <code class="docutils literal notranslate"><span class="pre">DurationField</span></code> 的值与 <code class="docutils literal notranslate"><span class="pre">DateTimeField</span></code> 实例上的算术进行比较，将无法达到预期的效果。</p>
</div>
</div>
<div class="section" id="s-emailfield">
<span id="emailfield"></span><h3><code class="docutils literal notranslate"><span class="pre">EmailField</span></code><a class="headerlink" href="#emailfield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.db.models.EmailField">
<em class="property">class </em><code class="descname">EmailField</code>(<em>max_length=254</em>, <em>**options</em>)<a class="headerlink" href="#django.db.models.EmailField" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>一个 <a class="reference internal" href="#django.db.models.CharField" title="django.db.models.CharField"><code class="xref py py-class docutils literal notranslate"><span class="pre">CharField</span></code></a>，使用 <a class="reference internal" href="../validators.html#django.core.validators.EmailValidator" title="django.core.validators.EmailValidator"><code class="xref py py-class docutils literal notranslate"><span class="pre">EmailValidator</span></code></a> 来检查该值是否为有效的电子邮件地址。</p>
</div>
<div class="section" id="s-filefield">
<span id="filefield"></span><h3><code class="docutils literal notranslate"><span class="pre">FileField</span></code><a class="headerlink" href="#filefield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.db.models.FileField">
<em class="property">class </em><code class="descname">FileField</code>(<em>upload_to=None</em>, <em>max_length=100</em>, <em>**options</em>)<a class="headerlink" href="#django.db.models.FileField" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>一个文件上传字段</p>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last"><code class="docutils literal notranslate"><span class="pre">primary_key</span></code> 参数不支持，如果使用，会引起错误。</p>
</div>
<p>有两个可选参数：</p>
<dl class="attribute">
<dt id="django.db.models.FileField.upload_to">
<code class="descclassname">FileField.</code><code class="descname">upload_to</code><a class="headerlink" href="#django.db.models.FileField.upload_to" title="永久链接至目标">¶</a></dt>
<dd><p>这个属性提供了一种设置上传目录和文件名的方式，可以有两种设置方式。在这两种情况下，值都会传递给 <a class="reference internal" href="../files/storage.html#django.core.files.storage.Storage.save" title="django.core.files.storage.Storage.save"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Storage.save()</span></code></a> 方法。</p>
<p>如果你指定一个字符串值或一个 <a class="reference external" href="https://docs.python.org/3/library/pathlib.html#pathlib.Path" title="(在 Python v3.9)"><code class="xref py py-class docutils literal notranslate"><span class="pre">Path</span></code></a>，它可能包含 <a class="reference external" href="https://docs.python.org/3/library/time.html#time.strftime" title="(在 Python v3.9)"><code class="xref py py-func docutils literal notranslate"><span class="pre">strftime()</span></code></a> 格式，它将被文件上传的日期／时间所代替（这样上传的文件就不会填满指定的目录）。例如：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">MyModel</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="c1"># file will be uploaded to MEDIA_ROOT/uploads</span>
    <span class="n">upload</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">FileField</span><span class="p">(</span><span class="n">upload_to</span><span class="o">=</span><span class="s1">&#39;uploads/&#39;</span><span class="p">)</span>
    <span class="c1"># or...</span>
    <span class="c1"># file will be saved to MEDIA_ROOT/uploads/2015/01/30</span>
    <span class="n">upload</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">FileField</span><span class="p">(</span><span class="n">upload_to</span><span class="o">=</span><span class="s1">&#39;uploads/%Y/%m/</span><span class="si">%d</span><span class="s1">/&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>如果你使用的是默认的 <a class="reference internal" href="../files/storage.html#django.core.files.storage.FileSystemStorage" title="django.core.files.storage.FileSystemStorage"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileSystemStorage</span></code></a>，这个字符串的值将被附加到你的 <a class="reference internal" href="../settings.html#std:setting-MEDIA_ROOT"><code class="xref std std-setting docutils literal notranslate"><span class="pre">MEDIA_ROOT</span></code></a> 路径后面，形成本地文件系统中上传文件的存储位置。如果你使用的是不同的存储系统，请检查该存储系统的文档，看看它是如何处理 <code class="docutils literal notranslate"><span class="pre">upload_to</span></code> 的。</p>
<p><code class="docutils literal notranslate"><span class="pre">upload_to</span></code> 也可以是一个可调用对象，如函数。这个函数将被调用以获得上传路径，包括文件名。这个可调用对象必须接受两个参数，并返回一个 Unix 风格的路径（带斜线），以便传给存储系统。这两个参数是：</p>
<table class="docutils">
<colgroup>
<col width="32%" />
<col width="68%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">参数</th>
<th class="head">描述</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">instance</span></code></td>
<td><p class="first">定义 <code class="docutils literal notranslate"><span class="pre">FileField</span></code> 的模型实例。更具体地说，这是附加当前文件的特定实例。</p>
<p class="last">在大多数情况下，这个对象还没有被保存到数据库，所以如果它使用默认的 <code class="docutils literal notranslate"><span class="pre">AutoField</span></code>，<em>它的主键字段可能还没有一个值</em>。</p>
</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">filename</span></code></td>
<td>最初给文件的文件名。在确定最终目标路径时，可能会考虑到，也可能不会考虑到。</td>
</tr>
</tbody>
</table>
<p>例子：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">user_directory_path</span><span class="p">(</span><span class="n">instance</span><span class="p">,</span> <span class="n">filename</span><span class="p">):</span>
    <span class="c1"># file will be uploaded to MEDIA_ROOT/user_&lt;id&gt;/&lt;filename&gt;</span>
    <span class="k">return</span> <span class="s1">&#39;user_</span><span class="si">{0}</span><span class="s1">/</span><span class="si">{1}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">instance</span><span class="o">.</span><span class="n">user</span><span class="o">.</span><span class="n">id</span><span class="p">,</span> <span class="n">filename</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">MyModel</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">upload</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">FileField</span><span class="p">(</span><span class="n">upload_to</span><span class="o">=</span><span class="n">user_directory_path</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<dl class="attribute">
<dt id="django.db.models.FileField.storage">
<code class="descclassname">FileField.</code><code class="descname">storage</code><a class="headerlink" href="#django.db.models.FileField.storage" title="永久链接至目标">¶</a></dt>
<dd><p>一个存储对象，或是一个返回存储对象的可调用对象。它处理你的文件的存储和检索。参见 <a class="reference internal" href="../../topics/files.html"><span class="doc">Managing files</span></a>，了解如何提供这个对象。</p>
<div class="versionchanged">
<span class="title">Changed in Django 3.1:</span> <p>增加了提供可调用对象的能力。</p>
</div>
</dd></dl>

<p>该字段的默认表单部件是一个 <a class="reference internal" href="../forms/widgets.html#django.forms.ClearableFileInput" title="django.forms.ClearableFileInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">ClearableFileInput</span></code></a>。</p>
<p>在模型中使用 <a class="reference internal" href="#django.db.models.FileField" title="django.db.models.FileField"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileField</span></code></a> 或 <a class="reference internal" href="#django.db.models.ImageField" title="django.db.models.ImageField"><code class="xref py py-class docutils literal notranslate"><span class="pre">ImageField</span></code></a> （见下文）需要几个步骤：</p>
<ol class="arabic simple">
<li>在你的配置文件中，你需要定义 <a class="reference internal" href="../settings.html#std:setting-MEDIA_ROOT"><code class="xref std std-setting docutils literal notranslate"><span class="pre">MEDIA_ROOT</span></code></a> 作为你希望 Django 存储上传文件的目录的完整路径。（为了保证性能，这些文件不存储在数据库中。）定义 <a class="reference internal" href="../settings.html#std:setting-MEDIA_URL"><code class="xref std std-setting docutils literal notranslate"><span class="pre">MEDIA_URL</span></code></a> 作为该目录的基本公共 URL。确保这个目录是 Web 服务器的用户账号可以写的。</li>
<li>将 <a class="reference internal" href="#django.db.models.FileField" title="django.db.models.FileField"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileField</span></code></a> 或 <a class="reference internal" href="#django.db.models.ImageField" title="django.db.models.ImageField"><code class="xref py py-class docutils literal notranslate"><span class="pre">ImageField</span></code></a> 添加到你的模型中，定义 <a class="reference internal" href="#django.db.models.FileField.upload_to" title="django.db.models.FileField.upload_to"><code class="xref py py-attr docutils literal notranslate"><span class="pre">upload_to</span></code></a> 选项，指定 <a class="reference internal" href="../settings.html#std:setting-MEDIA_ROOT"><code class="xref std std-setting docutils literal notranslate"><span class="pre">MEDIA_ROOT</span></code></a> 的子目录，用于上传文件。</li>
<li>所有这些将被存储在你的数据库中的是一个文件的路径（相对于 <a class="reference internal" href="../settings.html#std:setting-MEDIA_ROOT"><code class="xref std std-setting docutils literal notranslate"><span class="pre">MEDIA_ROOT</span></code></a> ）。你很可能要使用 Django 提供的方便的 <a class="reference internal" href="#django.db.models.fields.files.FieldFile.url" title="django.db.models.fields.files.FieldFile.url"><code class="xref py py-attr docutils literal notranslate"><span class="pre">url</span></code></a> 属性。例如，如果你的 <a class="reference internal" href="#django.db.models.ImageField" title="django.db.models.ImageField"><code class="xref py py-class docutils literal notranslate"><span class="pre">ImageField</span></code></a> 叫做 <code class="docutils literal notranslate"><span class="pre">mug_shot</span></code>，你可以在模板中使用 <code class="docutils literal notranslate"><span class="pre">{{</span> <span class="pre">object.mug_shot.url</span> <span class="pre">}}</span></code> 获取图片的绝对路径。</li>
</ol>
<p>例如，你的 <a class="reference internal" href="../settings.html#std:setting-MEDIA_ROOT"><code class="xref std std-setting docutils literal notranslate"><span class="pre">MEDIA_ROOT</span></code></a> 设置为 <code class="docutils literal notranslate"><span class="pre">'/home/media'</span></code>， <a class="reference internal" href="#django.db.models.FileField.upload_to" title="django.db.models.FileField.upload_to"><code class="xref py py-attr docutils literal notranslate"><span class="pre">upload_to</span></code></a> 设置为 <code class="docutils literal notranslate"><span class="pre">'photos/%Y/%m/%d'</span></code>。<a class="reference internal" href="#django.db.models.FileField.upload_to" title="django.db.models.FileField.upload_to"><code class="xref py py-attr docutils literal notranslate"><span class="pre">upload_to</span></code></a> 中的 <code class="docutils literal notranslate"><span class="pre">'%Y/%m/%d'</span></code> 部分是 <a class="reference external" href="https://docs.python.org/3/library/time.html#time.strftime" title="(在 Python v3.9)"><code class="xref py py-func docutils literal notranslate"><span class="pre">strftime()</span></code></a> 格式化，<code class="docutils literal notranslate"><span class="pre">'%Y'</span></code> 是四位数的年，<code class="docutils literal notranslate"><span class="pre">'%m'</span></code> 是两位数的月，<code class="docutils literal notranslate"><span class="pre">'%d'</span></code> 是两位数的日。如果你在 2007 年 1 月 15 日上传了一个文件，它将被保存在 <code class="docutils literal notranslate"><span class="pre">/home/media/photos/2007/01/15</span></code> 目录下。</p>
<p>如果你想检索上传文件的盘上文件名，或者文件的大小，可以分别使用 <a class="reference internal" href="../files/file.html#django.core.files.File.name" title="django.core.files.File.name"><code class="xref py py-attr docutils literal notranslate"><span class="pre">name</span></code></a> 和 <a class="reference internal" href="../files/file.html#django.core.files.File.size" title="django.core.files.File.size"><code class="xref py py-attr docutils literal notranslate"><span class="pre">size</span></code></a> 属性；关于可用属性和方法的更多信息，请参见 <a class="reference internal" href="../files/file.html#django.core.files.File" title="django.core.files.File"><code class="xref py py-class docutils literal notranslate"><span class="pre">File</span></code></a> 类参考和 <a class="reference internal" href="../../topics/files.html"><span class="doc">Managing files</span></a> 主题指南。</p>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">文件在数据库中作为保存模型的一部分，因此在模型被保存之前，不能依赖磁盘上使用的实际文件名。</p>
</div>
<p>上传的文件的相对 URL 可以通过 <code class="xref py py-attr docutils literal notranslate"><span class="pre">url</span></code> 属性获得。内部调用底层 <a class="reference internal" href="../files/storage.html#django.core.files.storage.Storage" title="django.core.files.storage.Storage"><code class="xref py py-class docutils literal notranslate"><span class="pre">Storage</span></code></a> 类的 <code class="xref py py-meth docutils literal notranslate"><span class="pre">store()</span></code> 方法。</p>
<p id="file-upload-security">需要注意的是，无论何时处理上传的文件，你都应该密切关注你上传的文件在哪里，是什么类型的文件，以避免安全漏洞。<em>对所有上传的文件进行验证</em>，这样你才能确定文件是你认为的那样。例如，如果你盲目地让别人上传文件，不经过验证，就上传文件到你的 Web 服务器的文档根目录下，那么有人就可以上传一个 CGI 或 PHP 脚本，并通过访问它的 URL 在你的网站上执行该脚本。不要允许这种情况发生。</p>
<p>另外要注意的是，即使是上传的 HTML 文件，由于可以被浏览器执行（虽然不能被服务器执行），也会造成相当于 XSS 或 CSRF 攻击的安全威胁。</p>
<p><a class="reference internal" href="#django.db.models.FileField" title="django.db.models.FileField"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileField</span></code></a> 实例在数据库中被创建为 <code class="docutils literal notranslate"><span class="pre">varchar</span></code> 列，默认最大长度为 100 个字符。与其他字段一样，你可以使用 <a class="reference internal" href="#django.db.models.CharField.max_length" title="django.db.models.CharField.max_length"><code class="xref py py-attr docutils literal notranslate"><span class="pre">max_length</span></code></a> 参数改变最大长度。</p>
<div class="section" id="s-filefield-and-fieldfile">
<span id="filefield-and-fieldfile"></span><h4><code class="docutils literal notranslate"><span class="pre">FileField</span></code> 和 <code class="docutils literal notranslate"><span class="pre">FieldFile</span></code><a class="headerlink" href="#filefield-and-fieldfile" title="永久链接至标题">¶</a></h4>
<dl class="class">
<dt id="django.db.models.fields.files.FieldFile">
<em class="property">class </em><code class="descname">FieldFile</code><a class="headerlink" href="#django.db.models.fields.files.FieldFile" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>当你访问一个模型上的 <a class="reference internal" href="#django.db.models.FileField" title="django.db.models.FileField"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileField</span></code></a> 时，你会得到一个 <a class="reference internal" href="#django.db.models.fields.files.FieldFile" title="django.db.models.fields.files.FieldFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">FieldFile</span></code></a> 的实例作为访问底层文件的代理。</p>
<p><a class="reference internal" href="#django.db.models.fields.files.FieldFile" title="django.db.models.fields.files.FieldFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">FieldFile</span></code></a> 的 API 与 <a class="reference internal" href="../files/file.html#django.core.files.File" title="django.core.files.File"><code class="xref py py-class docutils literal notranslate"><span class="pre">File</span></code></a> 的 API 相同，但有一个关键的区别。<em>该类所封装的对象不一定是 Python 内置文件对象的封装</em> 相反，它是 <code class="xref py py-attr docutils literal notranslate"><span class="pre">Storage.open()</span></code> 方法结果的封装，该方法可能是 <a class="reference internal" href="../files/file.html#django.core.files.File" title="django.core.files.File"><code class="xref py py-class docutils literal notranslate"><span class="pre">File</span></code></a> 对象，也可能是自定义存储对 <a class="reference internal" href="../files/file.html#django.core.files.File" title="django.core.files.File"><code class="xref py py-class docutils literal notranslate"><span class="pre">File</span></code></a> API 的实现。</p>
<p>除了从 <a class="reference internal" href="../files/file.html#django.core.files.File" title="django.core.files.File"><code class="xref py py-class docutils literal notranslate"><span class="pre">File</span></code></a> 继承的 API，如 <code class="docutils literal notranslate"><span class="pre">read()</span></code> 和 <code class="docutils literal notranslate"><span class="pre">write()</span></code> 之外，<a class="reference internal" href="#django.db.models.fields.files.FieldFile" title="django.db.models.fields.files.FieldFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">FieldFile</span></code></a> 还包括一些可以用来与底层文件交互的方法：</p>
<div class="admonition warning">
<p class="first admonition-title">警告</p>
<p class="last">该类的两个方法 <a class="reference internal" href="#django.db.models.fields.files.FieldFile.save" title="django.db.models.fields.files.FieldFile.save"><code class="xref py py-meth docutils literal notranslate"><span class="pre">save()</span></code></a> 和 <a class="reference internal" href="#django.db.models.fields.files.FieldFile.delete" title="django.db.models.fields.files.FieldFile.delete"><code class="xref py py-meth docutils literal notranslate"><span class="pre">delete()</span></code></a>，默认为将与相关 <code class="docutils literal notranslate"><span class="pre">FieldFile</span></code> 的模型对象保存在数据库中。</p>
</div>
<dl class="attribute">
<dt id="django.db.models.fields.files.FieldFile.name">
<code class="descclassname">FieldFile.</code><code class="descname">name</code><a class="headerlink" href="#django.db.models.fields.files.FieldFile.name" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>文件名，包括从关联的 <a class="reference internal" href="../files/storage.html#django.core.files.storage.Storage" title="django.core.files.storage.Storage"><code class="xref py py-class docutils literal notranslate"><span class="pre">Storage</span></code></a> 的根部开始的相对路径 <a class="reference internal" href="#django.db.models.FileField" title="django.db.models.FileField"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileField</span></code></a>。</p>
<dl class="attribute">
<dt id="django.db.models.fields.files.FieldFile.path">
<code class="descclassname">FieldFile.</code><code class="descname">path</code><a class="headerlink" href="#django.db.models.fields.files.FieldFile.path" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>一个只读属性，通过调用底层的 <a class="reference internal" href="../files/storage.html#django.core.files.storage.Storage.path" title="django.core.files.storage.Storage.path"><code class="xref py py-meth docutils literal notranslate"><span class="pre">path()</span></code></a> 方法，访问文件的本地文件系统路径。</p>
<dl class="attribute">
<dt id="django.db.models.fields.files.FieldFile.size">
<code class="descclassname">FieldFile.</code><code class="descname">size</code><a class="headerlink" href="#django.db.models.fields.files.FieldFile.size" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>底层 <a class="reference internal" href="../files/storage.html#django.core.files.storage.Storage.size" title="django.core.files.storage.Storage.size"><code class="xref py py-attr docutils literal notranslate"><span class="pre">Storage.size()</span></code></a> 方法的结果。</p>
<dl class="attribute">
<dt id="django.db.models.fields.files.FieldFile.url">
<code class="descclassname">FieldFile.</code><code class="descname">url</code><a class="headerlink" href="#django.db.models.fields.files.FieldFile.url" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>一个只读属性，通过调用底层 <a class="reference internal" href="../files/storage.html#django.core.files.storage.Storage" title="django.core.files.storage.Storage"><code class="xref py py-class docutils literal notranslate"><span class="pre">Storage</span></code></a> 类的 <a class="reference internal" href="../files/storage.html#django.core.files.storage.Storage" title="django.core.files.storage.Storage"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Storage()</span></code></a> 方法来访问文件的相对 URL。</p>
<dl class="method">
<dt id="django.db.models.fields.files.FieldFile.open">
<code class="descclassname">FieldFile.</code><code class="descname">open</code>(<em>mode='rb'</em>)<a class="headerlink" href="#django.db.models.fields.files.FieldFile.open" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>以指定的 <code class="docutils literal notranslate"><span class="pre">mode</span></code> 打开或重新打开与该实例相关的文件。与标准的 Python <code class="docutils literal notranslate"><span class="pre">open()</span></code> 方法不同，它不返回一个文件描述符。</p>
<p>因为在访问底层文件时，底层文件是隐式打开的，所以除了重置底层文件的指针或改变 <code class="docutils literal notranslate"><span class="pre">mode</span></code> 之外，可能没有必要调用这个方法。</p>
<dl class="method">
<dt id="django.db.models.fields.files.FieldFile.close">
<code class="descclassname">FieldFile.</code><code class="descname">close</code>()<a class="headerlink" href="#django.db.models.fields.files.FieldFile.close" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>类似于标准的 Python <code class="docutils literal notranslate"><span class="pre">file.close()</span></code> 方法，关闭与该实例相关的文件。</p>
<dl class="method">
<dt id="django.db.models.fields.files.FieldFile.save">
<code class="descclassname">FieldFile.</code><code class="descname">save</code>(<em>name</em>, <em>content</em>, <em>save=True</em>)<a class="headerlink" href="#django.db.models.fields.files.FieldFile.save" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>这个方法接收一个文件名和文件内容，并将它们传递给字段的存储类，然后将存储的文件与模型字段关联。如果你想手动将文件数据与模型上的 <a class="reference internal" href="#django.db.models.FileField" title="django.db.models.FileField"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileField</span></code></a> 实例关联起来，那么 <code class="docutils literal notranslate"><span class="pre">save()</span></code> 方法用来持久化该文件数据。</p>
<p>取两个必要的参数。<code class="docutils literal notranslate"><span class="pre">name</span></code> 是文件的名称，<code class="docutils literal notranslate"><span class="pre">content</span></code> 是包含文件内容的对象。 可选的 <code class="docutils literal notranslate"><span class="pre">save</span></code> 参数控制在与该字段相关联的文件被更改后是否保存模型实例。默认为 <code class="docutils literal notranslate"><span class="pre">True</span></code>。</p>
<p>注意 <code class="docutils literal notranslate"><span class="pre">content</span></code> 参数应该是 <a class="reference internal" href="../files/file.html#django.core.files.File" title="django.core.files.File"><code class="xref py py-class docutils literal notranslate"><span class="pre">django.core.files.File</span></code></a> 的实例，而不是 Python 内置的文件对象。你可以从现有的 Python 文件对象构造一个 <a class="reference internal" href="../files/file.html#django.core.files.File" title="django.core.files.File"><code class="xref py py-class docutils literal notranslate"><span class="pre">File</span></code></a>，像这样：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.core.files</span> <span class="kn">import</span> <span class="n">File</span>
<span class="c1"># Open an existing file using Python&#39;s built-in open()</span>
<span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;/path/to/hello.world&#39;</span><span class="p">)</span>
<span class="n">myfile</span> <span class="o">=</span> <span class="n">File</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
</pre></div>
</div>
<p>或者你可以从 Python 字符串中构建一个像这样的字符串：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.core.files.base</span> <span class="kn">import</span> <span class="n">ContentFile</span>
<span class="n">myfile</span> <span class="o">=</span> <span class="n">ContentFile</span><span class="p">(</span><span class="s2">&quot;hello world&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>更多信息，请参见 <a class="reference internal" href="../../topics/files.html"><span class="doc">Managing files</span></a>。</p>
<dl class="method">
<dt id="django.db.models.fields.files.FieldFile.delete">
<code class="descclassname">FieldFile.</code><code class="descname">delete</code>(<em>save=True</em>)<a class="headerlink" href="#django.db.models.fields.files.FieldFile.delete" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>删除与此实例相关的文件，并清除字段的所有属性。注意：如果在调用 <code class="docutils literal notranslate"><span class="pre">delete()</span></code> 时，文件恰好被打开，本方法将关闭该文件。</p>
<p>可选的 <code class="docutils literal notranslate"><span class="pre">save</span></code> 参数控制在删除与该字段相关的文件后是否保存模型实例。默认值为 <code class="docutils literal notranslate"><span class="pre">True</span></code>。</p>
<p>请注意，当一个模型被删除时，相关文件不会被删除。如果你需要清理遗留文件，你需要自己处理（例如，使用自定义管理命令，可以手动运行或通过例如 cron 定期运行）。</p>
</div>
</div>
<div class="section" id="s-filepathfield">
<span id="filepathfield"></span><h3><code class="docutils literal notranslate"><span class="pre">FilePathField</span></code><a class="headerlink" href="#filepathfield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.db.models.FilePathField">
<em class="property">class </em><code class="descname">FilePathField</code>(<em>path=''</em>, <em>match=None</em>, <em>recursive=False</em>, <em>allow_files=True</em>, <em>allow_folders=False</em>, <em>max_length=100</em>, <em>**options</em>)<a class="headerlink" href="#django.db.models.FilePathField" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>一个 <a class="reference internal" href="#django.db.models.CharField" title="django.db.models.CharField"><code class="xref py py-class docutils literal notranslate"><span class="pre">CharField</span></code></a>，其选择仅限于文件系统中某个目录下的文件名。有一些特殊的参数，其中第一个参数是 <strong>必须的</strong>。</p>
<dl class="attribute">
<dt id="django.db.models.FilePathField.path">
<code class="descclassname">FilePathField.</code><code class="descname">path</code><a class="headerlink" href="#django.db.models.FilePathField.path" title="永久链接至目标">¶</a></dt>
<dd><p>必须的。一个目录的绝对文件系统路径，这个 <a class="reference internal" href="#django.db.models.FilePathField" title="django.db.models.FilePathField"><code class="xref py py-class docutils literal notranslate"><span class="pre">FilePathField</span></code></a> 应从该目录中获取其选择。例如：<code class="docutils literal notranslate"><span class="pre">&quot;/home/images&quot;</span></code>。</p>
<p><code class="docutils literal notranslate"><span class="pre">path</span></code> 也可以是一个可调用对象，可以是在运行时动态设置路径的函数。例如：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">os</span>
<span class="kn">from</span> <span class="nn">django.conf</span> <span class="kn">import</span> <span class="n">settings</span>
<span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">def</span> <span class="nf">images_path</span><span class="p">():</span>
    <span class="k">return</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">settings</span><span class="o">.</span><span class="n">LOCAL_FILE_DIR</span><span class="p">,</span> <span class="s1">&#39;images&#39;</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">MyModel</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">file</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">FilePathField</span><span class="p">(</span><span class="n">path</span><span class="o">=</span><span class="n">images_path</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<dl class="attribute">
<dt id="django.db.models.FilePathField.match">
<code class="descclassname">FilePathField.</code><code class="descname">match</code><a class="headerlink" href="#django.db.models.FilePathField.match" title="永久链接至目标">¶</a></dt>
<dd><p>可选。一个正则表达式，作为一个字符串， <a class="reference internal" href="#django.db.models.FilePathField" title="django.db.models.FilePathField"><code class="xref py py-class docutils literal notranslate"><span class="pre">FilePathField</span></code></a> 将用于过滤文件名。请注意，正则表达式将被应用于基本文件名，而不是完整的路径。例如：<code class="docutils literal notranslate"><span class="pre">&quot;foo.*.txt$&quot;</span></code>，它将匹配名为 <code class="docutils literal notranslate"><span class="pre">foo23.txt</span></code> 的文件，但不匹配 <code class="docutils literal notranslate"><span class="pre">bar.txt</span></code> 或 <code class="docutils literal notranslate"><span class="pre">foo23.png</span></code>。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.db.models.FilePathField.recursive">
<code class="descclassname">FilePathField.</code><code class="descname">recursive</code><a class="headerlink" href="#django.db.models.FilePathField.recursive" title="永久链接至目标">¶</a></dt>
<dd><p>可选。<code class="docutils literal notranslate"><span class="pre">True</span></code> 或 <code class="docutils literal notranslate"><span class="pre">False</span></code>。默认为 <code class="docutils literal notranslate"><span class="pre">False</span></code>。指定是否包含 <a class="reference internal" href="#django.db.models.FilePathField.path" title="django.db.models.FilePathField.path"><code class="xref py py-attr docutils literal notranslate"><span class="pre">path</span></code></a> 的所有子目录。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.db.models.FilePathField.allow_files">
<code class="descclassname">FilePathField.</code><code class="descname">allow_files</code><a class="headerlink" href="#django.db.models.FilePathField.allow_files" title="永久链接至目标">¶</a></dt>
<dd><p>可选。 <code class="docutils literal notranslate"><span class="pre">True</span></code> 或 <code class="docutils literal notranslate"><span class="pre">False</span></code>。 默认值是 <code class="docutils literal notranslate"><span class="pre">True</span></code>。 指定是否应该包含指定位置的文件。 这个或 <a class="reference internal" href="#django.db.models.FilePathField.allow_folders" title="django.db.models.FilePathField.allow_folders"><code class="xref py py-attr docutils literal notranslate"><span class="pre">allow_folders</span></code></a> 必须是 <code class="docutils literal notranslate"><span class="pre">True</span></code>。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.db.models.FilePathField.allow_folders">
<code class="descclassname">FilePathField.</code><code class="descname">allow_folders</code><a class="headerlink" href="#django.db.models.FilePathField.allow_folders" title="永久链接至目标">¶</a></dt>
<dd><p>可选。 <code class="docutils literal notranslate"><span class="pre">True</span></code> 或 <code class="docutils literal notranslate"><span class="pre">False</span></code>。 默认为 <code class="docutils literal notranslate"><span class="pre">False</span></code>。 指定是否应该包含指定位置的文件夹。 这个或 <a class="reference internal" href="#django.db.models.FilePathField.allow_files" title="django.db.models.FilePathField.allow_files"><code class="xref py py-attr docutils literal notranslate"><span class="pre">allow_files</span></code></a> 必须是 <code class="docutils literal notranslate"><span class="pre">True</span></code>。</p>
</dd></dl>

<p>一个潜在的问题是 <a class="reference internal" href="#django.db.models.FilePathField.match" title="django.db.models.FilePathField.match"><code class="xref py py-attr docutils literal notranslate"><span class="pre">match</span></code></a> 适用于基本文件名，而不是完整的路径。所以，这个例子：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">FilePathField</span><span class="p">(</span><span class="n">path</span><span class="o">=</span><span class="s2">&quot;/home/images&quot;</span><span class="p">,</span> <span class="n">match</span><span class="o">=</span><span class="s2">&quot;foo.*&quot;</span><span class="p">,</span> <span class="n">recursive</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</pre></div>
</div>
<p>...将匹配 <code class="docutils literal notranslate"><span class="pre">/home/images/foo.png</span></code>，但不匹配 <code class="docutils literal notranslate"><span class="pre">/home/images/foo/bar.png</span></code>，因为 <a class="reference internal" href="#django.db.models.FilePathField.match" title="django.db.models.FilePathField.match"><code class="xref py py-attr docutils literal notranslate"><span class="pre">match</span></code></a> 适用于基本文件名（ <code class="docutils literal notranslate"><span class="pre">foo.png</span></code> 和 <code class="docutils literal notranslate"><span class="pre">bar.png</span></code> ）。</p>
<p><a class="reference internal" href="#django.db.models.FilePathField" title="django.db.models.FilePathField"><code class="xref py py-class docutils literal notranslate"><span class="pre">FilePathField</span></code></a> 实例在数据库中作为 <code class="docutils literal notranslate"><span class="pre">varchar</span></code> 列创建，默认最大长度为 100 个字符。与其他字段一样，你可以使用 <a class="reference internal" href="#django.db.models.CharField.max_length" title="django.db.models.CharField.max_length"><code class="xref py py-attr docutils literal notranslate"><span class="pre">max_length</span></code></a> 参数改变最大长度。</p>
</div>
<div class="section" id="s-floatfield">
<span id="floatfield"></span><h3><code class="docutils literal notranslate"><span class="pre">FloatField</span></code><a class="headerlink" href="#floatfield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.db.models.FloatField">
<em class="property">class </em><code class="descname">FloatField</code>(<em>**options</em>)<a class="headerlink" href="#django.db.models.FloatField" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>在 Python 中用一个 <code class="docutils literal notranslate"><span class="pre">float</span></code> 实例表示的浮点数。</p>
<p>当 <a class="reference internal" href="../forms/fields.html#django.forms.Field.localize" title="django.forms.Field.localize"><code class="xref py py-attr docutils literal notranslate"><span class="pre">localize</span></code></a> 为 <code class="docutils literal notranslate"><span class="pre">False</span></code> 时是 <a class="reference internal" href="../forms/widgets.html#django.forms.NumberInput" title="django.forms.NumberInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">NumberInput</span></code></a> 否则，该字段的默认表单部件是 <a class="reference internal" href="../forms/widgets.html#django.forms.TextInput" title="django.forms.TextInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextInput</span></code></a>。</p>
<div class="admonition-floatfield-vs-decimalfield admonition" id="floatfield-vs-decimalfield">
<p class="first admonition-title"><code class="docutils literal notranslate"><span class="pre">FloatField</span></code> vs. <code class="docutils literal notranslate"><span class="pre">DecimalField</span></code></p>
<p class="last"><a class="reference internal" href="#django.db.models.FloatField" title="django.db.models.FloatField"><code class="xref py py-class docutils literal notranslate"><span class="pre">FloatField</span></code></a> 类有时会与 <a class="reference internal" href="#django.db.models.DecimalField" title="django.db.models.DecimalField"><code class="xref py py-class docutils literal notranslate"><span class="pre">DecimalField</span></code></a> 类混淆。虽然它们都表示实数，但它们表示的方式不同。<code class="docutils literal notranslate"><span class="pre">FloatField</span></code> 内部使用 Python 的 <code class="docutils literal notranslate"><span class="pre">float</span></code> 类型，而 <code class="docutils literal notranslate"><span class="pre">DecimalField</span></code> 则使用 Python 的 <code class="docutils literal notranslate"><span class="pre">Decimal</span></code> 类型。关于两者之间的区别，请参见 Python 的 <a class="reference external" href="https://docs.python.org/3/library/decimal.html#module-decimal" title="(在 Python v3.9)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">decimal</span></code></a> 模块的文档。</p>
</div>
</div>
<div class="section" id="s-imagefield">
<span id="imagefield"></span><h3><code class="docutils literal notranslate"><span class="pre">ImageField</span></code><a class="headerlink" href="#imagefield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.db.models.ImageField">
<em class="property">class </em><code class="descname">ImageField</code>(<em>upload_to=None</em>, <em>height_field=None</em>, <em>width_field=None</em>, <em>max_length=100</em>, <em>**options</em>)<a class="headerlink" href="#django.db.models.ImageField" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>继承 <a class="reference internal" href="#django.db.models.FileField" title="django.db.models.FileField"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileField</span></code></a> 的所有属性和方法，但也验证上传的对象是有效的图像。</p>
<p>除了 <a class="reference internal" href="#django.db.models.FileField" title="django.db.models.FileField"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileField</span></code></a> 的特殊属性外， <a class="reference internal" href="#django.db.models.ImageField" title="django.db.models.ImageField"><code class="xref py py-class docutils literal notranslate"><span class="pre">ImageField</span></code></a> 也有 <code class="docutils literal notranslate"><span class="pre">height</span></code> 和 <code class="docutils literal notranslate"><span class="pre">width</span></code> 属性。</p>
<p>为了方便查询这些属性，<a class="reference internal" href="#django.db.models.ImageField" title="django.db.models.ImageField"><code class="xref py py-class docutils literal notranslate"><span class="pre">ImageField</span></code></a> 有两个额外的可选参数。</p>
<dl class="attribute">
<dt id="django.db.models.ImageField.height_field">
<code class="descclassname">ImageField.</code><code class="descname">height_field</code><a class="headerlink" href="#django.db.models.ImageField.height_field" title="永久链接至目标">¶</a></dt>
<dd><p>模型字段的名称，每次保存模型实例时将自动填充图像的高度。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.db.models.ImageField.width_field">
<code class="descclassname">ImageField.</code><code class="descname">width_field</code><a class="headerlink" href="#django.db.models.ImageField.width_field" title="永久链接至目标">¶</a></dt>
<dd><p>模型字段的名称，每次保存模型实例时将自动填充图像的宽度。</p>
</dd></dl>

<p>需要 <a class="reference external" href="https://pillow.readthedocs.io/en/latest/">Pillow</a> 库。</p>
<p><a class="reference internal" href="#django.db.models.ImageField" title="django.db.models.ImageField"><code class="xref py py-class docutils literal notranslate"><span class="pre">ImageField</span></code></a> 实例在数据库中创建为 <code class="docutils literal notranslate"><span class="pre">varchar</span></code> 列，默认最大长度为 100 个字符。与其他字段一样，你可以使用 <a class="reference internal" href="#django.db.models.CharField.max_length" title="django.db.models.CharField.max_length"><code class="xref py py-attr docutils literal notranslate"><span class="pre">max_length</span></code></a> 参数改变最大长度。</p>
<p>该字段的默认表单部件是一个 <a class="reference internal" href="../forms/widgets.html#django.forms.ClearableFileInput" title="django.forms.ClearableFileInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">ClearableFileInput</span></code></a>。</p>
</div>
<div class="section" id="s-integerfield">
<span id="integerfield"></span><h3><code class="docutils literal notranslate"><span class="pre">IntegerField</span></code><a class="headerlink" href="#integerfield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.db.models.IntegerField">
<em class="property">class </em><code class="descname">IntegerField</code>(<em>**options</em>)<a class="headerlink" href="#django.db.models.IntegerField" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>一个整数。从 <code class="docutils literal notranslate"><span class="pre">-2147483648</span></code> 到 <code class="docutils literal notranslate"><span class="pre">2147483647</span></code> 的值在 Django 支持的所有数据库中都是安全的。</p>
<p>它使用 <a class="reference internal" href="../validators.html#django.core.validators.MinValueValidator" title="django.core.validators.MinValueValidator"><code class="xref py py-class docutils literal notranslate"><span class="pre">MinValueValidator</span></code></a> 和 <a class="reference internal" href="../validators.html#django.core.validators.MaxValueValidator" title="django.core.validators.MaxValueValidator"><code class="xref py py-class docutils literal notranslate"><span class="pre">MaxValueValidator</span></code></a> 根据默认数据库支持的值来验证输入。</p>
<p>当 <a class="reference internal" href="../forms/fields.html#django.forms.Field.localize" title="django.forms.Field.localize"><code class="xref py py-attr docutils literal notranslate"><span class="pre">localize</span></code></a> 为 <code class="docutils literal notranslate"><span class="pre">False</span></code> 时是 <a class="reference internal" href="../forms/widgets.html#django.forms.NumberInput" title="django.forms.NumberInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">NumberInput</span></code></a> 否则，该字段的默认表单部件是 <a class="reference internal" href="../forms/widgets.html#django.forms.TextInput" title="django.forms.TextInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextInput</span></code></a>。</p>
</div>
<div class="section" id="s-genericipaddressfield">
<span id="genericipaddressfield"></span><h3><code class="docutils literal notranslate"><span class="pre">GenericIPAddressField</span></code><a class="headerlink" href="#genericipaddressfield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.db.models.GenericIPAddressField">
<em class="property">class </em><code class="descname">GenericIPAddressField</code>(<em>protocol='both'</em>, <em>unpack_ipv4=False</em>, <em>**options</em>)<a class="headerlink" href="#django.db.models.GenericIPAddressField" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>IPv4 或 IPv6 地址，字符串格式（如 <code class="docutils literal notranslate"><span class="pre">192.0.2.30</span></code> 或 <code class="docutils literal notranslate"><span class="pre">2a02:42fe::4</span></code> ）。该字段的默认表单部件是一个 <a class="reference internal" href="../forms/widgets.html#django.forms.TextInput" title="django.forms.TextInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextInput</span></code></a>。</p>
<p>IPv6 地址规范化遵循 <span class="target" id="index-2"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc4291.html#section-2.2"><strong>RFC 4291#section-2.2</strong></a> 第 2.2 节，包括使用该节第 3 段建议的 IPv4 格式，如 <code class="docutils literal notranslate"><span class="pre">::fffff:192.0.2.0</span></code>。例如，<code class="docutils literal notranslate"><span class="pre">2001:0::0:01</span></code> 将被标准化为 <code class="docutils literal notranslate"><span class="pre">2001::1</span></code>，<code class="docutils literal notranslate"><span class="pre">::fffff:0a0a:0a0a</span></code> 将被标准化为 <code class="docutils literal notranslate"><span class="pre">::fffff:10.10.10.10</span></code>。所有字符都转换为小写。</p>
<dl class="attribute">
<dt id="django.db.models.GenericIPAddressField.protocol">
<code class="descclassname">GenericIPAddressField.</code><code class="descname">protocol</code><a class="headerlink" href="#django.db.models.GenericIPAddressField.protocol" title="永久链接至目标">¶</a></dt>
<dd><p>将有效输入限制为指定协议。接受的值是 <code class="docutils literal notranslate"><span class="pre">'both'</span></code> （默认）、<code class="docutils literal notranslate"><span class="pre">'IPv4'</span></code> 或 <code class="docutils literal notranslate"><span class="pre">'IPv6'</span></code>。匹配是不分大小写的。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.db.models.GenericIPAddressField.unpack_ipv4">
<code class="descclassname">GenericIPAddressField.</code><code class="descname">unpack_ipv4</code><a class="headerlink" href="#django.db.models.GenericIPAddressField.unpack_ipv4" title="永久链接至目标">¶</a></dt>
<dd><p>解压 IPv4 映射地址，如 <code class="docutils literal notranslate"><span class="pre">::fffff:192.0.2.1</span></code>。如果启用该选项，该地址将被解压为 <code class="docutils literal notranslate"><span class="pre">192.0.2.1</span></code>。默认为禁用。只有当 <code class="docutils literal notranslate"><span class="pre">protocol</span></code> 设置为 <code class="docutils literal notranslate"><span class="pre">'both'</span></code> 时才会启用。</p>
</dd></dl>

<p>如果允许空值，就必须允许 null 值，因为空值会被存储为 null。</p>
</div>
<div class="section" id="s-jsonfield">
<span id="jsonfield"></span><h3><code class="docutils literal notranslate"><span class="pre">JSONField</span></code><a class="headerlink" href="#jsonfield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.db.models.JSONField">
<em class="property">class </em><code class="descname">JSONField</code>(<em>encoder=None</em>, <em>decoder=None</em>, <em>**options</em>)<a class="headerlink" href="#django.db.models.JSONField" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<div class="versionadded">
<span class="title">New in Django 3.1.</span> </div>
<p>一个用于存储 JSON 编码数据的字段。在 Python 中，数据以其 Python 本地格式表示：字典、列表、字符串、数字、布尔值和 <code class="docutils literal notranslate"><span class="pre">None</span></code>。</p>
<p><code class="docutils literal notranslate"><span class="pre">JSONField</span></code> 在 MariaDB 10.2.7+、MySQL 5.7.8+、Oracle、PostgreSQL 和 SQLite（在 <a class="reference internal" href="../databases.html#sqlite-json1"><span class="std std-ref">JSON1 扩展被启用的情况下</span></a>）都支持。</p>
<dl class="attribute">
<dt id="django.db.models.JSONField.encoder">
<code class="descclassname">JSONField.</code><code class="descname">encoder</code><a class="headerlink" href="#django.db.models.JSONField.encoder" title="永久链接至目标">¶</a></dt>
<dd><p>一个可选的 <a class="reference external" href="https://docs.python.org/3/library/json.html#json.JSONEncoder" title="(在 Python v3.9)"><code class="xref py py-class docutils literal notranslate"><span class="pre">json.JSONEncoder</span></code></a> 子类，用于序列化标准 JSON 序列化器不支持的数据类型（例如 <code class="docutils literal notranslate"><span class="pre">datetime.datetime</span></code> 或 <a class="reference external" href="https://docs.python.org/3/library/uuid.html#uuid.UUID" title="(在 Python v3.9)"><code class="xref py py-class docutils literal notranslate"><span class="pre">UUID</span></code></a> ）。例如，你可以使用 <a class="reference internal" href="../../topics/serialization.html#django.core.serializers.json.DjangoJSONEncoder" title="django.core.serializers.json.DjangoJSONEncoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">DjangoJSONEncoder</span></code></a> 类。</p>
<p>默认为 <code class="docutils literal notranslate"><span class="pre">json.JSONEncoder</span></code>。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.db.models.JSONField.decoder">
<code class="descclassname">JSONField.</code><code class="descname">decoder</code><a class="headerlink" href="#django.db.models.JSONField.decoder" title="永久链接至目标">¶</a></dt>
<dd><p>一个可选的 <a class="reference external" href="https://docs.python.org/3/library/json.html#json.JSONDecoder" title="(在 Python v3.9)"><code class="xref py py-class docutils literal notranslate"><span class="pre">json.JSONDecoder</span></code></a> 子类，用于反序列化从数据库中获取的值。该值将采用自定义编码器选择的格式（通常是字符串）。你的反序列化可能需要考虑到你无法确定输入类型的事实。例如，你有可能返回一个 <code class="docutils literal notranslate"><span class="pre">datetime</span></code>，实际上是一个字符串，而这个字符串恰好与 <code class="docutils literal notranslate"><span class="pre">datetime</span></code> 选择的格式相同。</p>
<p>默认为 <code class="docutils literal notranslate"><span class="pre">json.JSONDecoder</span></code>。</p>
</dd></dl>

<p>如果你给字段一个 <a class="reference internal" href="#django.db.models.Field.default" title="django.db.models.Field.default"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default</span></code></a>，确保它是一个不可变的对象，比如 <code class="docutils literal notranslate"><span class="pre">str</span></code>，或者是一个每次返回一个新的可变对象的可调用对象，比如 <code class="docutils literal notranslate"><span class="pre">dict</span></code> 或一个函数。提供一个像 <code class="docutils literal notranslate"><span class="pre">default={}</span></code> 或 <code class="docutils literal notranslate"><span class="pre">default=[]</span></code> 这样的可改变的默认对象，在所有模型实例之间共享一个对象。</p>
<p>要在数据库中查询 <code class="docutils literal notranslate"><span class="pre">JSONField</span></code>，请看 <a class="reference internal" href="../../topics/db/queries.html#querying-jsonfield"><span class="std std-ref">Querying JSONField</span></a>。</p>
<div class="admonition-indexing admonition">
<p class="first admonition-title">索引</p>
<p class="last"><a class="reference internal" href="indexes.html#django.db.models.Index" title="django.db.models.Index"><code class="xref py py-class docutils literal notranslate"><span class="pre">Index</span></code></a> 和 <a class="reference internal" href="#django.db.models.Field.db_index" title="django.db.models.Field.db_index"><code class="xref py py-attr docutils literal notranslate"><span class="pre">Field.db_index</span></code></a> 都创建了一个 B 树索引，在查询 <code class="docutils literal notranslate"><span class="pre">JSONField</span></code> 的时候并不是特别有用。仅在 PostgreSQL 上，可以使用 <a class="reference internal" href="../contrib/postgres/indexes.html#django.contrib.postgres.indexes.GinIndex" title="django.contrib.postgres.indexes.GinIndex"><code class="xref py py-class docutils literal notranslate"><span class="pre">GinIndex</span></code></a> 比较适合。</p>
</div>
<div class="admonition-postgresql-users admonition">
<p class="first admonition-title">PostgreSQL 用户</p>
<p class="last">PostgreSQL 有两种基于 JSON 的原生数据类型： <code class="docutils literal notranslate"><span class="pre">json</span></code> 和 <code class="docutils literal notranslate"><span class="pre">jsonb</span></code>。<code class="docutils literal notranslate"><span class="pre">json</span></code> 和 <code class="docutils literal notranslate"><span class="pre">jsonb</span></code>。它们之间的主要区别在于它们的存储方式和查询方式。PostgreSQL 的 <code class="docutils literal notranslate"><span class="pre">json</span></code> 字段是作为 JSON 的原始字符串表示来存储的，当根据键来查询时，必须同时进行解码。<code class="docutils literal notranslate"><span class="pre">jsonb</span></code> 字段是基于 JSON 的实际结构存储的，它允许索引。这样做的代价是在写入 <code class="docutils literal notranslate"><span class="pre">jsonb</span></code> 字段时增加了一点成本。<code class="docutils literal notranslate"><span class="pre">JSONField</span></code> 使用 <code class="docutils literal notranslate"><span class="pre">jsonb</span></code>。</p>
</div>
<div class="admonition-oracle-users admonition">
<p class="first admonition-title">Oracle 用户</p>
<p class="last">Oracle 数据库不支持存储 JSON 标量值。只支持 JSON 对象和数组（在 Python 中使用 <a class="reference external" href="https://docs.python.org/3/library/stdtypes.html#dict" title="(在 Python v3.9)"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> 和 <a class="reference external" href="https://docs.python.org/3/library/stdtypes.html#list" title="(在 Python v3.9)"><code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code></a> 表示)。</p>
</div>
</div>
<div class="section" id="s-nullbooleanfield">
<span id="nullbooleanfield"></span><h3><code class="docutils literal notranslate"><span class="pre">NullBooleanField</span></code><a class="headerlink" href="#nullbooleanfield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.db.models.NullBooleanField">
<em class="property">class </em><code class="descname">NullBooleanField</code>(<em>**options</em>)<a class="headerlink" href="#django.db.models.NullBooleanField" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>就像 <a class="reference internal" href="#django.db.models.BooleanField" title="django.db.models.BooleanField"><code class="xref py py-class docutils literal notranslate"><span class="pre">BooleanField</span></code></a> 的 <code class="docutils literal notranslate"><span class="pre">null=True</span></code>。</p>
<div class="deprecated">
<p><span class="versionmodified">3.1 版后已移除: </span><code class="docutils literal notranslate"><span class="pre">NullBooleanField</span></code> 已被废弃，改为 <code class="docutils literal notranslate"><span class="pre">BooleanField(null=True)</span></code>。</p>
</div>
</div>
<div class="section" id="s-positivebigintegerfield">
<span id="positivebigintegerfield"></span><h3><code class="docutils literal notranslate"><span class="pre">PositiveBigIntegerField</span></code><a class="headerlink" href="#positivebigintegerfield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.db.models.PositiveBigIntegerField">
<em class="property">class </em><code class="descname">PositiveBigIntegerField</code>(<em>**options</em>)<a class="headerlink" href="#django.db.models.PositiveBigIntegerField" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<div class="versionadded">
<span class="title">New in Django 3.1.</span> </div>
<p>就像一个 <a class="reference internal" href="#django.db.models.PositiveIntegerField" title="django.db.models.PositiveIntegerField"><code class="xref py py-class docutils literal notranslate"><span class="pre">PositiveIntegerField</span></code></a>，但只允许在某一特定点下的值（依赖于数据库）。<code class="docutils literal notranslate"><span class="pre">0</span></code> 到 <code class="docutils literal notranslate"><span class="pre">9223372036854775807</span></code> 的值在 Django 支持的所有数据库中都是安全的。</p>
</div>
<div class="section" id="s-positiveintegerfield">
<span id="positiveintegerfield"></span><h3><code class="docutils literal notranslate"><span class="pre">PositiveIntegerField</span></code><a class="headerlink" href="#positiveintegerfield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.db.models.PositiveIntegerField">
<em class="property">class </em><code class="descname">PositiveIntegerField</code>(<em>**options</em>)<a class="headerlink" href="#django.db.models.PositiveIntegerField" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>就像 <a class="reference internal" href="#django.db.models.IntegerField" title="django.db.models.IntegerField"><code class="xref py py-class docutils literal notranslate"><span class="pre">IntegerField</span></code></a> 一样，但必须是正值或零（ <code class="docutils literal notranslate"><span class="pre">0</span></code> ）。从``0`` 到 <code class="docutils literal notranslate"><span class="pre">2147483647</span></code> 的值在 Django 支持的所有数据库中都是安全的。出于向后兼容的原因，接受 <code class="docutils literal notranslate"><span class="pre">0</span></code> 的值。</p>
</div>
<div class="section" id="s-positivesmallintegerfield">
<span id="positivesmallintegerfield"></span><h3><code class="docutils literal notranslate"><span class="pre">PositiveSmallIntegerField</span></code><a class="headerlink" href="#positivesmallintegerfield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.db.models.PositiveSmallIntegerField">
<em class="property">class </em><code class="descname">PositiveSmallIntegerField</code>(<em>**options</em>)<a class="headerlink" href="#django.db.models.PositiveSmallIntegerField" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>就像一个 <a class="reference internal" href="#django.db.models.PositiveIntegerField" title="django.db.models.PositiveIntegerField"><code class="xref py py-class docutils literal notranslate"><span class="pre">PositiveIntegerField</span></code></a>，但只允许在某一特定（数据库依赖的）点下取值。<code class="docutils literal notranslate"><span class="pre">0</span></code> 到 <code class="docutils literal notranslate"><span class="pre">32767</span></code> 的值在 Django 支持的所有数据库中都是安全的。</p>
</div>
<div class="section" id="s-slugfield">
<span id="slugfield"></span><h3><code class="docutils literal notranslate"><span class="pre">SlugField</span></code><a class="headerlink" href="#slugfield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.db.models.SlugField">
<em class="property">class </em><code class="descname">SlugField</code>(<em>max_length=50</em>, <em>**options</em>)<a class="headerlink" href="#django.db.models.SlugField" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p><a class="reference internal" href="../../glossary.html#term-slug"><span class="xref std std-term">Slug</span></a> 是一个报纸术语。slug 是一个简短的标签，只包含字母、数字、下划线或连字符。它们一般用于 URL 中。</p>
<p>像 CharField 一样，你可以指定 <a class="reference internal" href="#django.db.models.CharField.max_length" title="django.db.models.CharField.max_length"><code class="xref py py-attr docutils literal notranslate"><span class="pre">max_length</span></code></a> （也请阅读那一节中关于数据库可移植性和 <a class="reference internal" href="#django.db.models.CharField.max_length" title="django.db.models.CharField.max_length"><code class="xref py py-attr docutils literal notranslate"><span class="pre">max_length</span></code></a> 的说明）。如果没有指定 <a class="reference internal" href="#django.db.models.CharField.max_length" title="django.db.models.CharField.max_length"><code class="xref py py-attr docutils literal notranslate"><span class="pre">max_length</span></code></a>，Django 将使用默认长度 50。</p>
<p>意味着将 <a class="reference internal" href="#django.db.models.Field.db_index" title="django.db.models.Field.db_index"><code class="xref py py-attr docutils literal notranslate"><span class="pre">Field.db_index</span></code></a> 设置为 <code class="docutils literal notranslate"><span class="pre">True</span></code>。</p>
<p>基于其他值的值自动预填充一个 SlugField 通常是很有用的。 你可以在管理中使用 <a class="reference internal" href="../contrib/admin/index.html#django.contrib.admin.ModelAdmin.prepopulated_fields" title="django.contrib.admin.ModelAdmin.prepopulated_fields"><code class="xref py py-attr docutils literal notranslate"><span class="pre">prepopulated_fields</span></code></a> 来自动完成。</p>
<p>它使用 <a class="reference internal" href="../validators.html#django.core.validators.validate_slug" title="django.core.validators.validate_slug"><code class="xref py py-class docutils literal notranslate"><span class="pre">validate_slug</span></code></a> 或 <a class="reference internal" href="../validators.html#django.core.validators.validate_unicode_slug" title="django.core.validators.validate_unicode_slug"><code class="xref py py-class docutils literal notranslate"><span class="pre">validate_unicode_slug</span></code></a> 进行验证。</p>
<dl class="attribute">
<dt id="django.db.models.SlugField.allow_unicode">
<code class="descclassname">SlugField.</code><code class="descname">allow_unicode</code><a class="headerlink" href="#django.db.models.SlugField.allow_unicode" title="永久链接至目标">¶</a></dt>
<dd><p>如果是 <code class="docutils literal notranslate"><span class="pre">True</span></code>，该字段除了接受 ASCII 字母外，还接受 Unicode 字母。默认值为 <code class="docutils literal notranslate"><span class="pre">False</span></code>。</p>
</dd></dl>

</div>
<div class="section" id="s-smallautofield">
<span id="smallautofield"></span><h3><code class="docutils literal notranslate"><span class="pre">SmallAutoField</span></code><a class="headerlink" href="#smallautofield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.db.models.SmallAutoField">
<em class="property">class </em><code class="descname">SmallAutoField</code>(<em>**options</em>)<a class="headerlink" href="#django.db.models.SmallAutoField" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>就像一个 <a class="reference internal" href="#django.db.models.AutoField" title="django.db.models.AutoField"><code class="xref py py-class docutils literal notranslate"><span class="pre">AutoField</span></code></a>，但只允许值在一定（依赖于数据库）的限制下。<code class="docutils literal notranslate"><span class="pre">1</span></code> 到 <code class="docutils literal notranslate"><span class="pre">32767</span></code> 的值在 Django 支持的所有数据库中都是安全的。</p>
</div>
<div class="section" id="s-smallintegerfield">
<span id="smallintegerfield"></span><h3><code class="docutils literal notranslate"><span class="pre">SmallIntegerField</span></code><a class="headerlink" href="#smallintegerfield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.db.models.SmallIntegerField">
<em class="property">class </em><code class="descname">SmallIntegerField</code>(<em>**options</em>)<a class="headerlink" href="#django.db.models.SmallIntegerField" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>就像一个 <a class="reference internal" href="#django.db.models.IntegerField" title="django.db.models.IntegerField"><code class="xref py py-class docutils literal notranslate"><span class="pre">IntegerField</span></code></a>，但只允许在某一特定（依赖于数据库的）点下取值。从 <code class="docutils literal notranslate"><span class="pre">-32768</span></code> 到 <code class="docutils literal notranslate"><span class="pre">32767</span></code> 的值在 Django 支持的所有数据库中都是安全的。</p>
</div>
<div class="section" id="s-textfield">
<span id="textfield"></span><h3><code class="docutils literal notranslate"><span class="pre">TextField</span></code><a class="headerlink" href="#textfield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.db.models.TextField">
<em class="property">class </em><code class="descname">TextField</code>(<em>**options</em>)<a class="headerlink" href="#django.db.models.TextField" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>一个大的文本字段。该字段的默认表单部件是一个 <a class="reference internal" href="../forms/widgets.html#django.forms.Textarea" title="django.forms.Textarea"><code class="xref py py-class docutils literal notranslate"><span class="pre">Textarea</span></code></a>。</p>
<p>如果你指定了 <code class="docutils literal notranslate"><span class="pre">max_length</span></code> 属性，它将反映在自动生成的表单字段的 <a class="reference internal" href="../forms/widgets.html#django.forms.Textarea" title="django.forms.Textarea"><code class="xref py py-class docutils literal notranslate"><span class="pre">Textarea</span></code></a> 部件中。但是，它并没有在模型或数据库层面被强制执行。使用一个 <a class="reference internal" href="#django.db.models.CharField" title="django.db.models.CharField"><code class="xref py py-class docutils literal notranslate"><span class="pre">CharField</span></code></a> 来实现。</p>
<dl class="attribute">
<dt id="django.db.models.TextField.db_collation">
<code class="descclassname">TextField.</code><code class="descname">db_collation</code><a class="headerlink" href="#django.db.models.TextField.db_collation" title="永久链接至目标">¶</a></dt>
<dd><div class="versionadded">
<span class="title">New in Django 3.2.</span> </div>
<p>该字段的数据库字符序名称。</p>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">字符序名称是不标准化的。因此，这将无法在多个数据库后端之间进行移植。</p>
</div>
<div class="admonition-oracle admonition">
<p class="first admonition-title">Oracle</p>
<p class="last">Oracle 不支持 <code class="docutils literal notranslate"><span class="pre">TextField</span></code> 的字符序。</p>
</div>
</dd></dl>

</div>
<div class="section" id="s-timefield">
<span id="timefield"></span><h3><code class="docutils literal notranslate"><span class="pre">TimeField</span></code><a class="headerlink" href="#timefield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.db.models.TimeField">
<em class="property">class </em><code class="descname">TimeField</code>(<em>auto_now=False</em>, <em>auto_now_add=False</em>, <em>**options</em>)<a class="headerlink" href="#django.db.models.TimeField" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>一个时间，在 Python 中用 <code class="docutils literal notranslate"><span class="pre">datetime.time</span></code> 实例表示。接受与 <a class="reference internal" href="#django.db.models.DateField" title="django.db.models.DateField"><code class="xref py py-class docutils literal notranslate"><span class="pre">DateField</span></code></a> 相同的自动填充选项。</p>
<p>该字段默认的表单部件t是一个 <a class="reference internal" href="../forms/widgets.html#django.forms.TimeInput" title="django.forms.TimeInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">TimeInput</span></code></a>。管理中添加了一些 JavaScript 快捷方式。</p>
</div>
<div class="section" id="s-urlfield">
<span id="urlfield"></span><h3><code class="docutils literal notranslate"><span class="pre">URLField</span></code><a class="headerlink" href="#urlfield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.db.models.URLField">
<em class="property">class </em><code class="descname">URLField</code>(<em>max_length=200</em>, <em>**options</em>)<a class="headerlink" href="#django.db.models.URLField" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>URL 的 <a class="reference internal" href="#django.db.models.CharField" title="django.db.models.CharField"><code class="xref py py-class docutils literal notranslate"><span class="pre">CharField</span></code></a>，由 <a class="reference internal" href="../validators.html#django.core.validators.URLValidator" title="django.core.validators.URLValidator"><code class="xref py py-class docutils literal notranslate"><span class="pre">URLValidator</span></code></a> 验证。</p>
<p>该字段的默认表单部件是一个 <a class="reference internal" href="../forms/widgets.html#django.forms.URLInput" title="django.forms.URLInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">URLInput</span></code></a>。</p>
<p>像所有的 <a class="reference internal" href="#django.db.models.CharField" title="django.db.models.CharField"><code class="xref py py-class docutils literal notranslate"><span class="pre">CharField</span></code></a> 子类一样， <a class="reference internal" href="#django.db.models.URLField" title="django.db.models.URLField"><code class="xref py py-class docutils literal notranslate"><span class="pre">URLField</span></code></a> 接受可选的 <a class="reference internal" href="#django.db.models.CharField.max_length" title="django.db.models.CharField.max_length"><code class="xref py py-attr docutils literal notranslate"><span class="pre">max_length</span></code></a> 参数。如果你没有指定 <a class="reference internal" href="#django.db.models.CharField.max_length" title="django.db.models.CharField.max_length"><code class="xref py py-attr docutils literal notranslate"><span class="pre">max_length</span></code></a> 参数，则使用默认的 200。</p>
</div>
<div class="section" id="s-uuidfield">
<span id="uuidfield"></span><h3><code class="docutils literal notranslate"><span class="pre">UUIDField</span></code><a class="headerlink" href="#uuidfield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.db.models.UUIDField">
<em class="property">class </em><code class="descname">UUIDField</code>(<em>**options</em>)<a class="headerlink" href="#django.db.models.UUIDField" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>一个用于存储通用唯一标识符的字段。使用 Python 的 <a class="reference external" href="https://docs.python.org/3/library/uuid.html#uuid.UUID" title="(在 Python v3.9)"><code class="xref py py-class docutils literal notranslate"><span class="pre">UUID</span></code></a> 类。当在 PostgreSQL 上使用时，它存储在一个 <code class="docutils literal notranslate"><span class="pre">uuid</span></code> 的数据类型中，否则存储在一个 <code class="docutils literal notranslate"><span class="pre">char(32)</span></code> 中。</p>
<p>通用唯一标识符是 <a class="reference internal" href="#django.db.models.Field.primary_key" title="django.db.models.Field.primary_key"><code class="xref py py-attr docutils literal notranslate"><span class="pre">primary_key</span></code></a> 的 <a class="reference internal" href="#django.db.models.AutoField" title="django.db.models.AutoField"><code class="xref py py-class docutils literal notranslate"><span class="pre">AutoField</span></code></a> 的一个很好的替代方案。数据库不会为你生成 UUID，所以建议使用 <a class="reference internal" href="#django.db.models.Field.default" title="django.db.models.Field.default"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default</span></code></a> ：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">uuid</span>
<span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">MyUUIDModel</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="nb">id</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">UUIDField</span><span class="p">(</span><span class="n">primary_key</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="n">uuid</span><span class="o">.</span><span class="n">uuid4</span><span class="p">,</span> <span class="n">editable</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
    <span class="c1"># other fields</span>
</pre></div>
</div>
<p>请注意，一个可调用对象（省略括号）被传递给 <code class="docutils literal notranslate"><span class="pre">default</span></code>，而不是 <code class="docutils literal notranslate"><span class="pre">UUID</span></code> 的实例。</p>
<div class="admonition-lookups-on-postgresql admonition">
<p class="first admonition-title">在 PostgreSQL 上查找</p>
<p class="last">在 PostgreSQL 上使用 <a class="reference internal" href="querysets.html#std:fieldlookup-iexact"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">iexact</span></code></a>、<a class="reference internal" href="querysets.html#std:fieldlookup-contains"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">contains</span></code></a>、<a class="reference internal" href="querysets.html#std:fieldlookup-icontains"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">icontains</span></code></a>、<a class="reference internal" href="querysets.html#std:fieldlookup-startswith"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">startswith</span></code></a>、<a class="reference internal" href="querysets.html#std:fieldlookup-istartswith"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">istartswith</span></code></a>、<a class="reference internal" href="querysets.html#std:fieldlookup-endswith"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">endswith</span></code></a> 或 <a class="reference internal" href="querysets.html#std:fieldlookup-iendswith"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">iendswith</span></code></a> 在 PostgreSQL 上查找没有连字符的值是行不通的，因为 PostgreSQL 将它们存储在一个连字符的 uuid 数据类型中。</p>
</div>
</div>
</div>
<div class="section" id="s-module-django.db.models.fields.related">
<span id="s-relationship-fields"></span><span id="module-django.db.models.fields.related"></span><span id="relationship-fields"></span><h2>关系字段<a class="headerlink" href="#module-django.db.models.fields.related" title="永久链接至标题">¶</a></h2>
<p>Django 还定义了一组表示关系的字段。</p>
<div class="section" id="s-foreignkey">
<span id="s-ref-foreignkey"></span><span id="foreignkey"></span><span id="ref-foreignkey"></span><h3><code class="docutils literal notranslate"><span class="pre">ForeignKey</span></code><a class="headerlink" href="#foreignkey" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.db.models.ForeignKey">
<em class="property">class </em><code class="descname">ForeignKey</code>(<em>to</em>, <em>on_delete</em>, <em>**options</em>)<a class="headerlink" href="#django.db.models.ForeignKey" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>一个多对一的关系。需要两个位置参数：模型相关的类和 <a class="reference internal" href="#django.db.models.ForeignKey.on_delete" title="django.db.models.ForeignKey.on_delete"><code class="xref py py-attr docutils literal notranslate"><span class="pre">on_delete</span></code></a> 选项。</p>
<p id="recursive-relationships">要创建一个递归关系——一个与自己有多对一关系的对象——使用 <code class="docutils literal notranslate"><span class="pre">models.ForeignKey('self',</span> <span class="pre">on_delete=models.CASCADE)</span></code>。</p>
<p id="lazy-relationships">如果你需要在一个尚未定义的模型上创建关系，你可以使用模型的名称，而不是模型对象本身：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Car</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">manufacturer</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span>
        <span class="s1">&#39;Manufacturer&#39;</span><span class="p">,</span>
        <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">,</span>
    <span class="p">)</span>
    <span class="c1"># ...</span>

<span class="k">class</span> <span class="nc">Manufacturer</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="c1"># ...</span>
    <span class="k">pass</span>
</pre></div>
</div>
<p>在 <a class="reference internal" href="../../topics/db/models.html#abstract-base-classes"><span class="std std-ref">抽象模型</span></a> 上以这种方式定义的关系在模型被子类化为具体模型时得到解析，与抽象模型的 <code class="docutils literal notranslate"><span class="pre">app_label</span></code> 不是相关的：</p>
<div class="literal-block-wrapper docutils container" id="id3">
<div class="code-block-caption"><span class="caption-text">products/models.py</span><a class="headerlink" href="#id3" title="永久链接至代码">¶</a></div>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">AbstractCar</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">manufacturer</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="s1">&#39;Manufacturer&#39;</span><span class="p">,</span> <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">)</span>

    <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
        <span class="n">abstract</span> <span class="o">=</span> <span class="kc">True</span>
</pre></div>
</div>
</div>
<div class="literal-block-wrapper docutils container" id="id4">
<div class="code-block-caption"><span class="caption-text">production/models.py</span><a class="headerlink" href="#id4" title="永久链接至代码">¶</a></div>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>
<span class="kn">from</span> <span class="nn">products.models</span> <span class="kn">import</span> <span class="n">AbstractCar</span>

<span class="k">class</span> <span class="nc">Manufacturer</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="k">pass</span>

<span class="k">class</span> <span class="nc">Car</span><span class="p">(</span><span class="n">AbstractCar</span><span class="p">):</span>
    <span class="k">pass</span>

<span class="c1"># Car.manufacturer will point to `production.Manufacturer` here.</span>
</pre></div>
</div>
</div>
<p>要引用定义在另一个应用程序中的模型，你可以明确地用完整的应用程序标签指定一个模型。例如，如果上面的 <code class="docutils literal notranslate"><span class="pre">Manufacturer</span></code> 模型是在另一个叫做 <code class="docutils literal notranslate"><span class="pre">production</span></code> 的应用程序中定义的，你需要使用：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Car</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">manufacturer</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span>
        <span class="s1">&#39;production.Manufacturer&#39;</span><span class="p">,</span>
        <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">,</span>
    <span class="p">)</span>
</pre></div>
</div>
<p>这种被称为懒惰关系的引用，在解决两个应用程序之间的循环导入依赖关系时很有用。</p>
<p>在 <code class="docutils literal notranslate"><span class="pre">ForeignKey</span></code> 上会自动创建一个数据库索引。你可以通过设置 <a class="reference internal" href="#django.db.models.Field.db_index" title="django.db.models.Field.db_index"><code class="xref py py-attr docutils literal notranslate"><span class="pre">db_index</span></code></a> 为 <code class="docutils literal notranslate"><span class="pre">False</span></code> 来禁用它。 如果你创建外键是为了保持一致性，而不是为了连接，或者你将创建一个替代性的索引，如部分索引或多列索引，你可能希望避免索引的开销。</p>
<div class="section" id="s-database-representation">
<span id="database-representation"></span><h4>数据库表现<a class="headerlink" href="#database-representation" title="永久链接至标题">¶</a></h4>
<p>在幕后，Django 在字段名后附加 <code class="docutils literal notranslate"><span class="pre">&quot;_id&quot;</span></code> 来创建数据库列名。在上面的例子中，<code class="docutils literal notranslate"><span class="pre">Car</span></code> 模型的数据库表将有一个 <code class="docutils literal notranslate"><span class="pre">manufacturer_id</span></code> 列。（你可以通过指定 <a class="reference internal" href="#django.db.models.Field.db_column" title="django.db.models.Field.db_column"><code class="xref py py-attr docutils literal notranslate"><span class="pre">db_column</span></code></a> 来显式地改变这一点）然而，你的代码应该永远不需要处理数据库列名，除非你编写自定义 SQL。你将总是处理你的模型对象的字段名。</p>
</div>
<div class="section" id="s-arguments">
<span id="s-foreign-key-arguments"></span><span id="arguments"></span><span id="foreign-key-arguments"></span><h4>参数<a class="headerlink" href="#arguments" title="永久链接至标题">¶</a></h4>
<p><a class="reference internal" href="#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a> 接受其他定义关系工作细节的参数。</p>
<dl class="attribute">
<dt id="django.db.models.ForeignKey.on_delete">
<code class="descclassname">ForeignKey.</code><code class="descname">on_delete</code><a class="headerlink" href="#django.db.models.ForeignKey.on_delete" title="永久链接至目标">¶</a></dt>
<dd><p>当一个由 <a class="reference internal" href="#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a> 引用的对象被删除时，Django 将模拟 <a class="reference internal" href="#django.db.models.ForeignKey.on_delete" title="django.db.models.ForeignKey.on_delete"><code class="xref py py-attr docutils literal notranslate"><span class="pre">on_delete</span></code></a> 参数所指定的 SQL 约束的行为。例如，如果你有一个可空的 <a class="reference internal" href="#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a>，并且你希望当被引用的对象被删除时，它被设置为空：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">user</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span>
    <span class="n">User</span><span class="p">,</span>
    <span class="n">models</span><span class="o">.</span><span class="n">SET_NULL</span><span class="p">,</span>
    <span class="n">blank</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span>
    <span class="n">null</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span>
<span class="p">)</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">on_delete</span></code> 不会在数据库中创建 SQL 约束。支持数据库级联选项 <a class="reference external" href="https://code.djangoproject.com/ticket/21961">可能会在以后实施</a>。</p>
</dd></dl>

<p><a class="reference internal" href="#django.db.models.ForeignKey.on_delete" title="django.db.models.ForeignKey.on_delete"><code class="xref py py-attr docutils literal notranslate"><span class="pre">on_delete</span></code></a> 的可能值可以在 <a class="reference internal" href="../../topics/db/models.html#module-django.db.models" title="django.db.models"><code class="xref py py-mod docutils literal notranslate"><span class="pre">django.db.models</span></code></a> 中找到。</p>
<ul>
<li><dl class="attribute">
<dt id="django.db.models.CASCADE">
<code class="descname">CASCADE</code><a class="headerlink" href="#django.db.models.CASCADE" title="永久链接至目标">¶</a></dt>
<dd><p>级联删除。Django 模拟了 SQL 约束 ON DELETE CASCADE 的行为，也删除了包含 ForeignKey 的对象。</p>
<p><a class="reference internal" href="instances.html#django.db.models.Model.delete" title="django.db.models.Model.delete"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Model.delete()</span></code></a> 在相关的模型上没有被调用，但是 <code class="xref py py-data docutils literal notranslate"><span class="pre">pre_delete</span></code> 和 <code class="xref py py-data docutils literal notranslate"><span class="pre">post_delete</span></code> 信号是为所有被删除的对象发送的。</p>
</dd></dl>

</li>
<li><dl class="attribute">
<dt id="django.db.models.PROTECT">
<code class="descname">PROTECT</code><a class="headerlink" href="#django.db.models.PROTECT" title="永久链接至目标">¶</a></dt>
<dd><p>通过引发 <a class="reference internal" href="../exceptions.html#django.db.models.ProtectedError" title="django.db.models.ProtectedError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ProtectedError</span></code></a>，即 <a class="reference internal" href="../exceptions.html#django.db.IntegrityError" title="django.db.IntegrityError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">django.db.IntegrityError</span></code></a> 的子类，防止删除被引用对象。</p>
</dd></dl>

</li>
<li><dl class="attribute">
<dt id="django.db.models.RESTRICT">
<code class="descname">RESTRICT</code><a class="headerlink" href="#django.db.models.RESTRICT" title="永久链接至目标">¶</a></dt>
<dd><div class="versionadded">
<span class="title">New in Django 3.1.</span> </div>
<p>通过引发 <a class="reference internal" href="../exceptions.html#django.db.models.RestrictedError" title="django.db.models.RestrictedError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RestrictedError</span></code></a> （ <a class="reference internal" href="../exceptions.html#django.db.IntegrityError" title="django.db.IntegrityError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">django.db.IntegrityError</span></code></a> 的一个子类）来防止删除被引用的对象。与 <a class="reference internal" href="#django.db.models.PROTECT" title="django.db.models.PROTECT"><code class="xref py py-attr docutils literal notranslate"><span class="pre">PROTECT</span></code></a> 不同的是，如果被引用的对象也引用了一个在同一操作中被删除的不同对象，但通过 <a class="reference internal" href="#django.db.models.CASCADE" title="django.db.models.CASCADE"><code class="xref py py-attr docutils literal notranslate"><span class="pre">CASCADE</span></code></a> 关系，则允许删除被引用的对象。</p>
<p>思考下下面这组模型：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Artist</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">10</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">Album</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">artist</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">Artist</span><span class="p">,</span> <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">Song</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">artist</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">Artist</span><span class="p">,</span> <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">)</span>
    <span class="n">album</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">Album</span><span class="p">,</span> <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">RESTRICT</span><span class="p">)</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">Artist</span></code> 可以被删除，即使这意味着删除被 <code class="docutils literal notranslate"><span class="pre">Song</span></code> 引用的 <code class="docutils literal notranslate"><span class="pre">Album</span></code>，因为 <code class="docutils literal notranslate"><span class="pre">Song</span></code> 也通过级联关系引用 <code class="docutils literal notranslate"><span class="pre">Artist</span></code> 本身。例如：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">artist_one</span> <span class="o">=</span> <span class="n">Artist</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;artist one&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">artist_two</span> <span class="o">=</span> <span class="n">Artist</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;artist two&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">album_one</span> <span class="o">=</span> <span class="n">Album</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">artist</span><span class="o">=</span><span class="n">artist_one</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">album_two</span> <span class="o">=</span> <span class="n">Album</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">artist</span><span class="o">=</span><span class="n">artist_two</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">song_one</span> <span class="o">=</span> <span class="n">Song</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">artist</span><span class="o">=</span><span class="n">artist_one</span><span class="p">,</span> <span class="n">album</span><span class="o">=</span><span class="n">album_one</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">song_two</span> <span class="o">=</span> <span class="n">Song</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">artist</span><span class="o">=</span><span class="n">artist_one</span><span class="p">,</span> <span class="n">album</span><span class="o">=</span><span class="n">album_two</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">album_one</span><span class="o">.</span><span class="n">delete</span><span class="p">()</span>
<span class="go"># Raises RestrictedError.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">artist_two</span><span class="o">.</span><span class="n">delete</span><span class="p">()</span>
<span class="go"># Raises RestrictedError.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">artist_one</span><span class="o">.</span><span class="n">delete</span><span class="p">()</span>
<span class="go">(4, {&#39;Song&#39;: 2, &#39;Album&#39;: 1, &#39;Artist&#39;: 1})</span>
</pre></div>
</div>
</dd></dl>

</li>
<li><dl class="attribute">
<dt id="django.db.models.SET_NULL">
<code class="descname">SET_NULL</code><a class="headerlink" href="#django.db.models.SET_NULL" title="永久链接至目标">¶</a></dt>
<dd><p>设置 <a class="reference internal" href="#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a> 为空；只有当 <a class="reference internal" href="#django.db.models.Field.null" title="django.db.models.Field.null"><code class="xref py py-attr docutils literal notranslate"><span class="pre">null</span></code></a> 为 <code class="docutils literal notranslate"><span class="pre">True</span></code> 时，才有可能。</p>
</dd></dl>

</li>
<li><dl class="attribute">
<dt id="django.db.models.SET_DEFAULT">
<code class="descname">SET_DEFAULT</code><a class="headerlink" href="#django.db.models.SET_DEFAULT" title="永久链接至目标">¶</a></dt>
<dd><p>将 <a class="reference internal" href="#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a> 设置为默认值，必须为 <a class="reference internal" href="#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a> 设置一个默认值。</p>
</dd></dl>

</li>
<li><dl class="function">
<dt id="django.db.models.SET">
<code class="descname">SET</code>()<a class="headerlink" href="#django.db.models.SET" title="永久链接至目标">¶</a></dt>
<dd><p>将 <a class="reference internal" href="#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a> 设置为传递给 <a class="reference internal" href="#django.db.models.SET" title="django.db.models.SET"><code class="xref py py-func docutils literal notranslate"><span class="pre">SET()</span></code></a> 的值，如果传递了一个可调用的值，则为调用它的结果。在大多数情况下，为了避免在导入 models.py 时执行查询，传递一个可调用对象是必要的：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.conf</span> <span class="kn">import</span> <span class="n">settings</span>
<span class="kn">from</span> <span class="nn">django.contrib.auth</span> <span class="kn">import</span> <span class="n">get_user_model</span>
<span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">def</span> <span class="nf">get_sentinel_user</span><span class="p">():</span>
    <span class="k">return</span> <span class="n">get_user_model</span><span class="p">()</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get_or_create</span><span class="p">(</span><span class="n">username</span><span class="o">=</span><span class="s1">&#39;deleted&#39;</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span>

<span class="k">class</span> <span class="nc">MyModel</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">user</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span>
        <span class="n">settings</span><span class="o">.</span><span class="n">AUTH_USER_MODEL</span><span class="p">,</span>
        <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">SET</span><span class="p">(</span><span class="n">get_sentinel_user</span><span class="p">),</span>
    <span class="p">)</span>
</pre></div>
</div>
</dd></dl>

</li>
<li><dl class="attribute">
<dt id="django.db.models.DO_NOTHING">
<code class="descname">DO_NOTHING</code><a class="headerlink" href="#django.db.models.DO_NOTHING" title="永久链接至目标">¶</a></dt>
<dd><p>不采取任何行动。如果你的数据库后端强制执行引用完整性，这将导致一个 <a class="reference internal" href="../exceptions.html#django.db.IntegrityError" title="django.db.IntegrityError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IntegrityError</span></code></a> 除非你手动添加一个 SQL <code class="docutils literal notranslate"><span class="pre">ON</span> <span class="pre">DELETE</span></code> 约束条件到数据库字段。</p>
</dd></dl>

</li>
</ul>
<dl class="attribute">
<dt id="django.db.models.ForeignKey.limit_choices_to">
<code class="descclassname">ForeignKey.</code><code class="descname">limit_choices_to</code><a class="headerlink" href="#django.db.models.ForeignKey.limit_choices_to" title="永久链接至目标">¶</a></dt>
<dd><p>当使用 <code class="docutils literal notranslate"><span class="pre">ModelForm</span></code> 或管理中渲染该字段时，设置该字段的可用选择限制（默认情况下，查询集中的所有对象都可以选择）。可以使用字典、 <a class="reference internal" href="querysets.html#django.db.models.Q" title="django.db.models.Q"><code class="xref py py-class docutils literal notranslate"><span class="pre">Q</span></code></a> 对象，或者返回字典或 <a class="reference internal" href="querysets.html#django.db.models.Q" title="django.db.models.Q"><code class="xref py py-class docutils literal notranslate"><span class="pre">Q</span></code></a> 对象的可调用对象。</p>
<p>例子：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">staff_member</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span>
    <span class="n">User</span><span class="p">,</span>
    <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">,</span>
    <span class="n">limit_choices_to</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;is_staff&#39;</span><span class="p">:</span> <span class="kc">True</span><span class="p">},</span>
<span class="p">)</span>
</pre></div>
</div>
<p>导致 <code class="docutils literal notranslate"><span class="pre">ModelForm</span></code> 上的对应字段只列出有 <code class="docutils literal notranslate"><span class="pre">is_staff=True</span></code> 的 <code class="docutils literal notranslate"><span class="pre">Users</span></code>。这在 Django 管理中可能会有帮助。</p>
<p>例如，当与 Python <code class="docutils literal notranslate"><span class="pre">datetime</span></code> 模块一起使用时，可调用对象可以很有帮助，通过日期范围限制选择。例如：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">limit_pub_date_choices</span><span class="p">():</span>
    <span class="k">return</span> <span class="p">{</span><span class="s1">&#39;pub_date__lte&#39;</span><span class="p">:</span> <span class="n">datetime</span><span class="o">.</span><span class="n">date</span><span class="o">.</span><span class="n">today</span><span class="p">()}</span>

<span class="n">limit_choices_to</span> <span class="o">=</span> <span class="n">limit_pub_date_choices</span>
</pre></div>
</div>
<p>如果 <code class="docutils literal notranslate"><span class="pre">limit_choices_to</span></code> 是或返回一个 <a class="reference internal" href="querysets.html#django.db.models.Q" title="django.db.models.Q"><code class="xref py py-class docutils literal notranslate"><span class="pre">Q对象</span></code></a>，这对 <a class="reference internal" href="../../topics/db/queries.html#complex-lookups-with-q"><span class="std std-ref">复杂的查询</span></a> 很有用，那么只有当该字段没有在 <code class="docutils literal notranslate"><span class="pre">ModelAdmin</span></code> 中的 <a class="reference internal" href="../contrib/admin/index.html#django.contrib.admin.ModelAdmin.raw_id_fields" title="django.contrib.admin.ModelAdmin.raw_id_fields"><code class="xref py py-attr docutils literal notranslate"><span class="pre">raw_id_fields</span></code></a> 中列出时，它才会对管理中可用的选择产生影响。</p>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">如果 <code class="docutils literal notranslate"><span class="pre">limit_choices_to</span></code> 使用了可调用对象，那么每次实例化一个新的表单时，都会调用该功能。它也可以在模型被验证时被调用，例如由管理命令或管理中调用。管理中构建查询集来多次验证各种边缘情况下的表单输入，所以你的可调用对象有可能会被多次调用。</p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="django.db.models.ForeignKey.related_name">
<code class="descclassname">ForeignKey.</code><code class="descname">related_name</code><a class="headerlink" href="#django.db.models.ForeignKey.related_name" title="永久链接至目标">¶</a></dt>
<dd><p>用于从相关对象到这个对象的关系的名称。这也是 <a class="reference internal" href="#django.db.models.ForeignKey.related_query_name" title="django.db.models.ForeignKey.related_query_name"><code class="xref py py-attr docutils literal notranslate"><span class="pre">related_query_name</span></code></a> 的默认值（用于从目标模型反向过滤名称的名称）。请参阅 <a class="reference internal" href="../../topics/db/queries.html#backwards-related-objects"><span class="std std-ref">关联对象文档</span></a> 以获得完整的解释和示例。请注意，当你在 <span class="xref std std-ref">抽象模型</span> 是可用的。</p>
<p>如果你不希望 Django 创建一个反向关系，可以将 <code class="docutils literal notranslate"><span class="pre">related_name</span></code> 设置为 <code class="docutils literal notranslate"><span class="pre">'+'</span></code> 或者以 <code class="docutils literal notranslate"><span class="pre">'+'</span></code> 结束。例如，这将确保 <code class="docutils literal notranslate"><span class="pre">User</span></code> 模型不会与这个模型有反向关系：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">user</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span>
    <span class="n">User</span><span class="p">,</span>
    <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">,</span>
    <span class="n">related_name</span><span class="o">=</span><span class="s1">&#39;+&#39;</span><span class="p">,</span>
<span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<dl class="attribute">
<dt id="django.db.models.ForeignKey.related_query_name">
<code class="descclassname">ForeignKey.</code><code class="descname">related_query_name</code><a class="headerlink" href="#django.db.models.ForeignKey.related_query_name" title="永久链接至目标">¶</a></dt>
<dd><p>目标模型中反向过滤器的名称。如果设置了，它默认为 <a class="reference internal" href="#django.db.models.ForeignKey.related_name" title="django.db.models.ForeignKey.related_name"><code class="xref py py-attr docutils literal notranslate"><span class="pre">related_name</span></code></a> 或 <a class="reference internal" href="options.html#django.db.models.Options.default_related_name" title="django.db.models.Options.default_related_name"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default_related_name</span></code></a> 的值，否则默认为模型的名称：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Declare the ForeignKey with related_query_name</span>
<span class="k">class</span> <span class="nc">Tag</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">article</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span>
        <span class="n">Article</span><span class="p">,</span>
        <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">,</span>
        <span class="n">related_name</span><span class="o">=</span><span class="s2">&quot;tags&quot;</span><span class="p">,</span>
        <span class="n">related_query_name</span><span class="o">=</span><span class="s2">&quot;tag&quot;</span><span class="p">,</span>
    <span class="p">)</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">255</span><span class="p">)</span>

<span class="c1"># That&#39;s now the name of the reverse filter</span>
<span class="n">Article</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">tag__name</span><span class="o">=</span><span class="s2">&quot;important&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>和 <a class="reference internal" href="#django.db.models.ForeignKey.related_name" title="django.db.models.ForeignKey.related_name"><code class="xref py py-attr docutils literal notranslate"><span class="pre">related_name</span></code></a> 一样，<code class="docutils literal notranslate"><span class="pre">related_query_name</span></code> 通过 <a class="reference internal" href="../../topics/db/models.html#abstract-related-name"><span class="std std-ref">一些特殊的语法</span></a> 支持应用标签和类的插值。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.db.models.ForeignKey.to_field">
<code class="descclassname">ForeignKey.</code><code class="descname">to_field</code><a class="headerlink" href="#django.db.models.ForeignKey.to_field" title="永久链接至目标">¶</a></dt>
<dd><p>关联对象的字段。默认情况下，Django 使用相关对象的主键。如果你引用了一个不同的字段，这个字段必须有 <code class="docutils literal notranslate"><span class="pre">unique=True</span></code>。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.db.models.ForeignKey.db_constraint">
<code class="descclassname">ForeignKey.</code><code class="descname">db_constraint</code><a class="headerlink" href="#django.db.models.ForeignKey.db_constraint" title="永久链接至目标">¶</a></dt>
<dd><p>控制是否应该在数据库中为这个外键创建一个约束。默认值是 <code class="docutils literal notranslate"><span class="pre">True</span></code>，这几乎是你想要的；将其设置为 <code class="docutils literal notranslate"><span class="pre">False</span></code> 对数据完整性非常不利。话虽如此，下面是一些你可能想要这样做的情况：</p>
<ul class="simple">
<li>你有无效的冗余数据</li>
<li>你正在共享你的数据库</li>
</ul>
<p>如果将此设置为 <code class="docutils literal notranslate"><span class="pre">False</span></code>，访问一个不存在的相关对象将引发 <code class="docutils literal notranslate"><span class="pre">DoesNotExist</span></code> 异常。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.db.models.ForeignKey.swappable">
<code class="descclassname">ForeignKey.</code><code class="descname">swappable</code><a class="headerlink" href="#django.db.models.ForeignKey.swappable" title="永久链接至目标">¶</a></dt>
<dd><p>控制迁移框架的反应，如果这个 <a class="reference internal" href="#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a> 指向一个可交换的模型。如果它是 <code class="docutils literal notranslate"><span class="pre">True</span></code> ——默认值-——那么如果 <a class="reference internal" href="#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a> 指向的模型与 <code class="docutils literal notranslate"><span class="pre">settings.AUTH_USER_MODEL</span></code> 的当前值相匹配（或其他可互换模型配置），则关系将在迁移中使用对配置的引用而不是直接对模型进行存储。</p>
<p>只有当你确定你的模型应该始终指向交换的模型——例如，如果它是一个专门为你的自定义用户模型设计的配置文件模型，你才希望将此覆盖为 <code class="docutils literal notranslate"><span class="pre">False</span></code>。</p>
<p>将它设置为 <code class="docutils literal notranslate"><span class="pre">False</span></code> 并不意味着你可以引用一个可交换的模型，即使它被交换了—— <code class="docutils literal notranslate"><span class="pre">False</span></code> 意味着用这个外键进行的迁移将始终引用你指定的确切模型（所以如果用户试图用你不支持的 User 模型运行，它将失败，例如）。</p>
<p>如果不确定，就保留它在默认为 <code class="docutils literal notranslate"><span class="pre">True</span></code> 的状态。</p>
</dd></dl>

</div>
</div>
<div class="section" id="s-manytomanyfield">
<span id="manytomanyfield"></span><h3><code class="docutils literal notranslate"><span class="pre">ManyToManyField</span></code><a class="headerlink" href="#manytomanyfield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.db.models.ManyToManyField">
<em class="property">class </em><code class="descname">ManyToManyField</code>(<em>to</em>, <em>**options</em>)<a class="headerlink" href="#django.db.models.ManyToManyField" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>一个多对多的关系。需要一个位置参数：模型相关的类，它的工作原理与 <a class="reference internal" href="#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a> 完全相同，包括 <a class="reference internal" href="#recursive-relationships"><span class="std std-ref">递归</span></a> 和 <a class="reference internal" href="#lazy-relationships"><span class="std std-ref">惰性</span></a> 关系。</p>
<p>可以通过字段的 <code class="xref py py-class docutils literal notranslate"><span class="pre">RelatedManager</span></code> 来添加、删除或创建相关对象。</p>
<div class="section" id="s-id1">
<span id="id1"></span><h4>数据库表现<a class="headerlink" href="#id1" title="永久链接至标题">¶</a></h4>
<p>在幕后，Django 创建了一个中间连接表来表示多对多的关系。默认情况下，这个表名是使用多对多字段的名称和包含它的模型的表名生成的。由于有些数据库不支持超过一定长度的表名，这些表名将被自动截断，并使用唯一性哈希，例如 <code class="docutils literal notranslate"><span class="pre">author_books_9cdf</span></code>。你可以使用 <a class="reference internal" href="#django.db.models.ManyToManyField.db_table" title="django.db.models.ManyToManyField.db_table"><code class="xref py py-attr docutils literal notranslate"><span class="pre">db_table</span></code></a> 选项手动提供连接表的名称。</p>
</div>
<div class="section" id="s-manytomany-arguments">
<span id="s-id2"></span><span id="manytomany-arguments"></span><span id="id2"></span><h4>参数<a class="headerlink" href="#manytomany-arguments" title="永久链接至标题">¶</a></h4>
<p><a class="reference internal" href="#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><code class="xref py py-class docutils literal notranslate"><span class="pre">ManyToManyField</span></code></a> 接受一组额外的参数——都是可选的——控制关系如何运作。</p>
<dl class="attribute">
<dt id="django.db.models.ManyToManyField.related_name">
<code class="descclassname">ManyToManyField.</code><code class="descname">related_name</code><a class="headerlink" href="#django.db.models.ManyToManyField.related_name" title="永久链接至目标">¶</a></dt>
<dd><p>与 <a class="reference internal" href="#django.db.models.ForeignKey.related_name" title="django.db.models.ForeignKey.related_name"><code class="xref py py-attr docutils literal notranslate"><span class="pre">ForeignKey.related_name</span></code></a> 相同。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.db.models.ManyToManyField.related_query_name">
<code class="descclassname">ManyToManyField.</code><code class="descname">related_query_name</code><a class="headerlink" href="#django.db.models.ManyToManyField.related_query_name" title="永久链接至目标">¶</a></dt>
<dd><p>与 <a class="reference internal" href="#django.db.models.ForeignKey.related_query_name" title="django.db.models.ForeignKey.related_query_name"><code class="xref py py-attr docutils literal notranslate"><span class="pre">ForeignKey.related_query_name</span></code></a> 相同。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.db.models.ManyToManyField.limit_choices_to">
<code class="descclassname">ManyToManyField.</code><code class="descname">limit_choices_to</code><a class="headerlink" href="#django.db.models.ManyToManyField.limit_choices_to" title="永久链接至目标">¶</a></dt>
<dd><p>与 <a class="reference internal" href="#django.db.models.ForeignKey.limit_choices_to" title="django.db.models.ForeignKey.limit_choices_to"><code class="xref py py-attr docutils literal notranslate"><span class="pre">ForeignKey.limit_choices_to</span></code></a> 相同。</p>
<p><code class="docutils literal notranslate"><span class="pre">limit_choices_to</span></code> 在使用 <a class="reference internal" href="#django.db.models.ManyToManyField.through" title="django.db.models.ManyToManyField.through"><code class="xref py py-attr docutils literal notranslate"><span class="pre">through</span></code></a> 参数指定自定义中间表的 <code class="docutils literal notranslate"><span class="pre">ManyToManyField</span></code> 上使用时没有效果。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.db.models.ManyToManyField.symmetrical">
<code class="descclassname">ManyToManyField.</code><code class="descname">symmetrical</code><a class="headerlink" href="#django.db.models.ManyToManyField.symmetrical" title="永久链接至目标">¶</a></dt>
<dd><p>仅在自身上定义多对多字段关系时。考虑以下模型</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Person</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">friends</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ManyToManyField</span><span class="p">(</span><span class="s2">&quot;self&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>当 Django 处理这个模型时，它识别出它本身有一个 <a class="reference internal" href="#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><code class="xref py py-class docutils literal notranslate"><span class="pre">ManyToManyField</span></code></a>，因此，它没有给 <code class="docutils literal notranslate"><span class="pre">Person</span></code> 类添加 <code class="docutils literal notranslate"><span class="pre">person_set</span></code> 属性。相反， <a class="reference internal" href="#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><code class="xref py py-class docutils literal notranslate"><span class="pre">ManyToManyField</span></code></a> 被认为是对称的，也就是说，如果我是你的朋友，那么你就是我的朋友。</p>
<p>如果你不想让 <code class="docutils literal notranslate"><span class="pre">self</span></code> 的多对多关系对称，可以将 <a class="reference internal" href="#django.db.models.ManyToManyField.symmetrical" title="django.db.models.ManyToManyField.symmetrical"><code class="xref py py-attr docutils literal notranslate"><span class="pre">symmetrical</span></code></a> 设置为 <code class="docutils literal notranslate"><span class="pre">False</span></code>。这样会强制 Django 添加反向关系的描述符，允许 <a class="reference internal" href="#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><code class="xref py py-class docutils literal notranslate"><span class="pre">ManyToManyField</span></code></a> 关系是非对称的。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.db.models.ManyToManyField.through">
<code class="descclassname">ManyToManyField.</code><code class="descname">through</code><a class="headerlink" href="#django.db.models.ManyToManyField.through" title="永久链接至目标">¶</a></dt>
<dd><p>Django 会自动生成一个表来管理多对多关系。但是，如果你想手动指定中间表，你可以使用 <a class="reference internal" href="#django.db.models.ManyToManyField.through" title="django.db.models.ManyToManyField.through"><code class="xref py py-attr docutils literal notranslate"><span class="pre">through</span></code></a> 选项来指定代表你要使用的中间表的 Django 模型。</p>
<p>这个选项最常见的用法是当你想把 <a class="reference internal" href="../../topics/db/models.html#intermediary-manytomany"><span class="std std-ref">额外的数据与多对多关系</span></a> 联系起来。</p>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">如果你不想让同一个实例之间有多个关联，可以添加一个 <a class="reference internal" href="constraints.html#django.db.models.UniqueConstraint" title="django.db.models.UniqueConstraint"><code class="xref py py-class docutils literal notranslate"><span class="pre">UniqueConstraint</span></code></a>，包括 from 和 to 字段。Django 自动生成的多对多表就包含了这样的约束。</p>
</div>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">使用代理模型的递归关系不能确定反向访问器的名称，因为它们会是相同的。你需要设置一个 <a class="reference internal" href="#django.db.models.ForeignKey.related_name" title="django.db.models.ForeignKey.related_name"><code class="xref py py-attr docutils literal notranslate"><span class="pre">related_name</span></code></a> 到其中至少一个。如果你希望 Django 不创建反向关系，请将 <code class="docutils literal notranslate"><span class="pre">related_name</span></code> 设置为 <code class="docutils literal notranslate"><span class="pre">'+'</span></code>。</p>
</div>
<p>如果你没有指定一个显式的 <code class="docutils literal notranslate"><span class="pre">through</span></code> 模型，你仍然可以使用一个隐式的 <code class="docutils literal notranslate"><span class="pre">through</span></code> 模型类来直接访问为保持关联而创建的表。它有三个字段来链接模型。</p>
<p>如果源模型和目标模型不同，则会生成以下字段：</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">id</span></code> ：关系的主键。</li>
<li><code class="docutils literal notranslate"><span class="pre">&lt;containing_model&gt;_id</span></code> ：声明 <code class="docutils literal notranslate"><span class="pre">ManyToManyField</span></code> 的模型的 <code class="docutils literal notranslate"><span class="pre">id</span></code>。</li>
<li><code class="docutils literal notranslate"><span class="pre">&lt;other_model&gt;_id</span></code> ：<code class="docutils literal notranslate"><span class="pre">ManyToManyField</span></code> 指向的模型的 <code class="docutils literal notranslate"><span class="pre">id</span></code>。</li>
</ul>
<p>如果 <code class="docutils literal notranslate"><span class="pre">ManyToManyField</span></code> 指向的来源和目标是相同的模型， 下面的字段会生成：</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">id</span></code> ：关系的主键。</li>
<li><code class="docutils literal notranslate"><span class="pre">from_&lt;model&gt;_id</span></code> ：指向模型的实例（即源实例）的 <code class="docutils literal notranslate"><span class="pre">id</span></code>。</li>
<li><code class="docutils literal notranslate"><span class="pre">to_&lt;model&gt;_id</span></code> ：关系所指向的实例（即目标模型实例）的 <code class="docutils literal notranslate"><span class="pre">id</span></code>。</li>
</ul>
<p>这个类可以像普通模型一样，用于查询给定模型实例的关联记录：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Model</span><span class="o">.</span><span class="n">m2mfield</span><span class="o">.</span><span class="n">through</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
</pre></div>
</div>
</dd></dl>

<dl class="attribute">
<dt id="django.db.models.ManyToManyField.through_fields">
<code class="descclassname">ManyToManyField.</code><code class="descname">through_fields</code><a class="headerlink" href="#django.db.models.ManyToManyField.through_fields" title="永久链接至目标">¶</a></dt>
<dd><p>只有当指定了一个自定义的中间模型时才会使用，Django 通常会决定使用中介模型的哪些字段来自动建立多对多的关系。然而，考虑以下模型：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Person</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">50</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">Group</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">128</span><span class="p">)</span>
    <span class="n">members</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ManyToManyField</span><span class="p">(</span>
        <span class="n">Person</span><span class="p">,</span>
        <span class="n">through</span><span class="o">=</span><span class="s1">&#39;Membership&#39;</span><span class="p">,</span>
        <span class="n">through_fields</span><span class="o">=</span><span class="p">(</span><span class="s1">&#39;group&#39;</span><span class="p">,</span> <span class="s1">&#39;person&#39;</span><span class="p">),</span>
    <span class="p">)</span>

<span class="k">class</span> <span class="nc">Membership</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">group</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">Group</span><span class="p">,</span> <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">)</span>
    <span class="n">person</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">Person</span><span class="p">,</span> <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">)</span>
    <span class="n">inviter</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span>
        <span class="n">Person</span><span class="p">,</span>
        <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">,</span>
        <span class="n">related_name</span><span class="o">=</span><span class="s2">&quot;membership_invites&quot;</span><span class="p">,</span>
    <span class="p">)</span>
    <span class="n">invite_reason</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">64</span><span class="p">)</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">Membership</span></code> 对 <code class="docutils literal notranslate"><span class="pre">Person</span></code> 有 <em>两个</em> 外键（ <code class="docutils literal notranslate"><span class="pre">person</span></code> 和 <code class="docutils literal notranslate"><span class="pre">inviter</span></code> ），这就使得两者的关系变得模糊不清，Django 无法知道应该使用哪个外键。在这种情况下，你必须使用 <code class="docutils literal notranslate"><span class="pre">through_fields</span></code> 明确指定 Django 应该使用哪个外键，就像上面的例子一样。</p>
<p><code class="docutils literal notranslate"><span class="pre">through_fields</span></code> 接受一个二元元组 <code class="docutils literal notranslate"><span class="pre">('field1',</span> <span class="pre">'field2')</span></code>，其中 <code class="docutils literal notranslate"><span class="pre">field1</span></code> 是定义在 <a class="reference internal" href="#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><code class="xref py py-class docutils literal notranslate"><span class="pre">ManyToManyField</span></code></a> 上的模型（本例中为 <code class="docutils literal notranslate"><span class="pre">group</span></code> ）的外键名称，<code class="docutils literal notranslate"><span class="pre">field2</span></code> 是目标模型（本例中为 <code class="docutils literal notranslate"><span class="pre">person</span></code> ）的外键名称。</p>
<p>当你在中间模型上有一个以上的外键到任何一个（甚至两个）参与多对多关系的模型时，你 <em>必须</em> 指定 <code class="docutils literal notranslate"><span class="pre">through_fields</span></code>。这也适用于 <a class="reference internal" href="#recursive-relationships"><span class="std std-ref">递归关系</span></a>，当使用一个中间模型，并且该模型有两个以上的外键，或者你想明确指定 Django 应该使用哪两个外键。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.db.models.ManyToManyField.db_table">
<code class="descclassname">ManyToManyField.</code><code class="descname">db_table</code><a class="headerlink" href="#django.db.models.ManyToManyField.db_table" title="永久链接至目标">¶</a></dt>
<dd><p>要创建的用于存储多对多数据的表的名称。如果没有提供这个表名，Django 将根据以下表名创建一个默认表名：定义关系的模型表和字段本身的名称。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.db.models.ManyToManyField.db_constraint">
<code class="descclassname">ManyToManyField.</code><code class="descname">db_constraint</code><a class="headerlink" href="#django.db.models.ManyToManyField.db_constraint" title="永久链接至目标">¶</a></dt>
<dd><p>控制是否应该在数据库中为中间表的外键创建约束。默认值是 <code class="docutils literal notranslate"><span class="pre">True</span></code>，这几乎是你想要的；将其设置为 <code class="docutils literal notranslate"><span class="pre">False</span></code> 对数据完整性非常不利。话说回来，下面是一些你可能想要这样做的情况：</p>
<ul class="simple">
<li>你有无效的冗余数据</li>
<li>你正在共享你的数据库</li>
</ul>
<p>同时传递 <code class="docutils literal notranslate"><span class="pre">db_constraint</span></code> 和 <code class="docutils literal notranslate"><span class="pre">through</span></code> 会引发错误。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.db.models.ManyToManyField.swappable">
<code class="descclassname">ManyToManyField.</code><code class="descname">swappable</code><a class="headerlink" href="#django.db.models.ManyToManyField.swappable" title="永久链接至目标">¶</a></dt>
<dd><p>控制迁移框架的反应，如果这个 <a class="reference internal" href="#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><code class="xref py py-class docutils literal notranslate"><span class="pre">ManyToManyField</span></code></a> 指向一个可交换的模型。如果它是 <code class="docutils literal notranslate"><span class="pre">True</span></code> ——默认值——那么如果 <a class="reference internal" href="#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><code class="xref py py-class docutils literal notranslate"><span class="pre">ManyToManyField</span></code></a> 指向的模型与 <code class="docutils literal notranslate"><span class="pre">settings.AUTH_USER_MODEL</span></code> 的当前值相匹配（或其他可交换模型配置），关系将被存储在迁移中，使用对配置的引用，而不是直接对模型的引用。</p>
<p>只有当你确定你的模型应该始终指向交换的模型——例如，如果它是一个专门为你的自定义用户模型设计的配置文件模型，你才希望将此覆盖为 <code class="docutils literal notranslate"><span class="pre">False</span></code>。</p>
<p>如果不确定，就保留它在默认为 <code class="docutils literal notranslate"><span class="pre">True</span></code> 的状态。</p>
</dd></dl>

<p><a class="reference internal" href="#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><code class="xref py py-class docutils literal notranslate"><span class="pre">ManyToManyField</span></code></a> 不支持 <a class="reference internal" href="#django.db.models.Field.validators" title="django.db.models.Field.validators"><code class="xref py py-attr docutils literal notranslate"><span class="pre">validators</span></code></a>。</p>
<p><a class="reference internal" href="#django.db.models.Field.null" title="django.db.models.Field.null"><code class="xref py py-attr docutils literal notranslate"><span class="pre">null</span></code></a> 没有效果，因为没有办法在数据库层面要求建立关系。</p>
</div>
</div>
<div class="section" id="s-onetoonefield">
<span id="onetoonefield"></span><h3><code class="docutils literal notranslate"><span class="pre">OneToOneField</span></code><a class="headerlink" href="#onetoonefield" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.db.models.OneToOneField">
<em class="property">class </em><code class="descname">OneToOneField</code>(<em>to</em>, <em>on_delete</em>, <em>parent_link=False</em>, <em>**options</em>)<a class="headerlink" href="#django.db.models.OneToOneField" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>一对一的关系。概念上，这类似于 <a class="reference internal" href="#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a> 与 <a class="reference internal" href="#django.db.models.Field.unique" title="django.db.models.Field.unique"><code class="xref py py-attr docutils literal notranslate"><span class="pre">unique=True</span></code></a>，但关系的“反向”将直接返回一个单一对象。</p>
<p>最有用的是作为某种方式“扩展”另一个模型的主键；<a class="reference internal" href="../../topics/db/models.html#multi-table-inheritance"><span class="std std-ref">Multi-table inheritance</span></a> 是通过添加一个从子模型到父模型的隐式一对一关系来实现的，例如：</p>
<p>需要一个位置参数：模型将与之相关的类。这与 <a class="reference internal" href="#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a> 的工作原理完全相同，包括关于 <a class="reference internal" href="#recursive-relationships"><span class="std std-ref">递归</span></a> 和 <a class="reference internal" href="#lazy-relationships"><span class="std std-ref">惰性</span></a> 关系的所有选项。</p>
<p>如果没有为 <code class="docutils literal notranslate"><span class="pre">OneToOneField</span></code> 指定 <a class="reference internal" href="#django.db.models.ForeignKey.related_name" title="django.db.models.ForeignKey.related_name"><code class="xref py py-attr docutils literal notranslate"><span class="pre">related_name</span></code></a> 参数，Django 将使用当前模型的小写名作为默认值。</p>
<p>举例如下：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.conf</span> <span class="kn">import</span> <span class="n">settings</span>
<span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">MySpecialUser</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">user</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">OneToOneField</span><span class="p">(</span>
        <span class="n">settings</span><span class="o">.</span><span class="n">AUTH_USER_MODEL</span><span class="p">,</span>
        <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">,</span>
    <span class="p">)</span>
    <span class="n">supervisor</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">OneToOneField</span><span class="p">(</span>
        <span class="n">settings</span><span class="o">.</span><span class="n">AUTH_USER_MODEL</span><span class="p">,</span>
        <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">,</span>
        <span class="n">related_name</span><span class="o">=</span><span class="s1">&#39;supervisor_of&#39;</span><span class="p">,</span>
    <span class="p">)</span>
</pre></div>
</div>
<p>你的 <code class="docutils literal notranslate"><span class="pre">User</span></code> 模型将有以下属性：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">user</span> <span class="o">=</span> <span class="n">User</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">hasattr</span><span class="p">(</span><span class="n">user</span><span class="p">,</span> <span class="s1">&#39;myspecialuser&#39;</span><span class="p">)</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">hasattr</span><span class="p">(</span><span class="n">user</span><span class="p">,</span> <span class="s1">&#39;supervisor_of&#39;</span><span class="p">)</span>
<span class="go">True</span>
</pre></div>
</div>
<p>当访问反向关系时，如果相关表中的条目不存在，就会引发一个 <code class="docutils literal notranslate"><span class="pre">RelatedObjectDoesNotExist</span></code> 异常。这是目标模型的 <a class="reference internal" href="class.html#django.db.models.Model.DoesNotExist" title="django.db.models.Model.DoesNotExist"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Model.DoesNotExist</span></code></a> 异常的一个子类。例如，如果一个用户没有一个由 <code class="docutils literal notranslate"><span class="pre">MySpecialUser</span></code> 指定的主管：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">user</span><span class="o">.</span><span class="n">supervisor_of</span>
<span class="gt">Traceback (most recent call last):</span>
    <span class="o">...</span>
<span class="gr">RelatedObjectDoesNotExist</span>: <span class="n">User has no supervisor_of.</span>
</pre></div>
</div>
<p id="onetoone-arguments">此外，<code class="docutils literal notranslate"><span class="pre">OneToOneField</span></code> 接受 <a class="reference internal" href="#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a> 接受的所有额外参数，外加一个额外参数：</p>
<dl class="attribute">
<dt id="django.db.models.OneToOneField.parent_link">
<code class="descclassname">OneToOneField.</code><code class="descname">parent_link</code><a class="headerlink" href="#django.db.models.OneToOneField.parent_link" title="永久链接至目标">¶</a></dt>
<dd><p>当 <code class="docutils literal notranslate"><span class="pre">True</span></code> 并用于从另一个 <a class="reference internal" href="../../glossary.html#term-concrete-model"><span class="xref std std-term">concrete model</span></a> 继承的模型中时，表示该字段应被用作回到父类的链接，而不是通常通过子类隐含创建的额外 <code class="docutils literal notranslate"><span class="pre">OneToOneField</span></code>。</p>
</dd></dl>

<p>参见 <a class="reference internal" href="../../topics/db/examples/one_to_one.html"><span class="doc">一对一关系</span></a>，了解 <code class="docutils literal notranslate"><span class="pre">OneToOneField</span></code> 的使用实例。</p>
</div>
</div>
<div class="section" id="s-field-api-reference">
<span id="field-api-reference"></span><h2>字段 API 参考<a class="headerlink" href="#field-api-reference" title="永久链接至标题">¶</a></h2>
<dl class="class">
<dt id="django.db.models.Field">
<em class="property">class </em><code class="descname">Field</code><a class="headerlink" href="#django.db.models.Field" title="永久链接至目标">¶</a></dt>
<dd><p><code class="docutils literal notranslate"><span class="pre">Field</span></code> 是一个抽象的类，表示一个数据库表的列。Django 使用字段来创建数据库表（ <a class="reference internal" href="#django.db.models.Field.db_type" title="django.db.models.Field.db_type"><code class="xref py py-meth docutils literal notranslate"><span class="pre">db_type()</span></code></a> ），将 Python 类型映射到数据库（ <a class="reference internal" href="#django.db.models.Field.get_prep_value" title="django.db.models.Field.get_prep_value"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_prep_value()</span></code></a> ），反之亦然（ <a class="reference internal" href="#django.db.models.Field.from_db_value" title="django.db.models.Field.from_db_value"><code class="xref py py-meth docutils literal notranslate"><span class="pre">from_db_value()</span></code></a> ）。</p>
<p>因此，一个字段在不同的 Django API 中是一个基本的部分，特别是 <a class="reference internal" href="instances.html#django.db.models.Model" title="django.db.models.Model"><code class="xref py py-class docutils literal notranslate"><span class="pre">models</span></code></a> 和 <a class="reference internal" href="querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">querysets</span></code></a>。</p>
<p>在模型中中，字段被实例化为一个类属性，并代表一个特定的表列，见 <a class="reference internal" href="../../topics/db/models.html"><span class="doc">Models</span></a>。它的属性有 <a class="reference internal" href="#django.db.models.Field.null" title="django.db.models.Field.null"><code class="xref py py-attr docutils literal notranslate"><span class="pre">null</span></code></a> 和 <a class="reference internal" href="#django.db.models.Field.unique" title="django.db.models.Field.unique"><code class="xref py py-attr docutils literal notranslate"><span class="pre">unique</span></code></a>，以及 Django 用来将字段值映射到数据库特定值的方法。</p>
<p><code class="docutils literal notranslate"><span class="pre">Field</span></code> 是 <a class="reference internal" href="lookups.html#django.db.models.lookups.RegisterLookupMixin" title="django.db.models.lookups.RegisterLookupMixin"><code class="xref py py-class docutils literal notranslate"><span class="pre">RegisterLookupMixin</span></code></a> 的子类，因此 <a class="reference internal" href="lookups.html#django.db.models.Transform" title="django.db.models.Transform"><code class="xref py py-class docutils literal notranslate"><span class="pre">Transform</span></code></a> 和 <a class="reference internal" href="lookups.html#django.db.models.Lookup" title="django.db.models.Lookup"><code class="xref py py-class docutils literal notranslate"><span class="pre">Lookup</span></code></a> 都可以在它上面注册，以便在 <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> 中使用（例如： <code class="docutils literal notranslate"><span class="pre">field_name__exact=&quot;foo&quot;</span></code> ）。所有 <a class="reference internal" href="querysets.html#field-lookups"><span class="std std-ref">内置查找</span></a> 都是默认注册的。</p>
<p>所有 Django 的内置字段，如 <a class="reference internal" href="#django.db.models.CharField" title="django.db.models.CharField"><code class="xref py py-class docutils literal notranslate"><span class="pre">CharField</span></code></a>，都是 <code class="docutils literal notranslate"><span class="pre">Field</span></code> 的特殊实现。如果你需要一个自定义的字段，你可以对任何一个内置字段进行子类化，或者从头开始写一个 <code class="docutils literal notranslate"><span class="pre">Field</span></code>。无论哪种情况，请参见 <a class="reference internal" href="../../howto/custom-model-fields.html"><span class="doc">编写自定义模型字段(model fields)</span></a>。</p>
<dl class="attribute">
<dt id="django.db.models.Field.description">
<code class="descname">description</code><a class="headerlink" href="#django.db.models.Field.description" title="永久链接至目标">¶</a></dt>
<dd><p>字段的详细描述，例如： <a class="reference internal" href="../contrib/admin/admindocs.html#module-django.contrib.admindocs" title="django.contrib.admindocs: Django's admin documentation generator."><code class="xref py py-mod docutils literal notranslate"><span class="pre">django.contrib.admindocs</span></code></a> 应用程序。</p>
<p>描述的形式可以是：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">description</span> <span class="o">=</span> <span class="n">_</span><span class="p">(</span><span class="s2">&quot;String (up to </span><span class="si">%(max_length)s</span><span class="s2">)&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>其中的参数是从字段的 <code class="docutils literal notranslate"><span class="pre">__dict__</span></code> 中插入的。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.db.models.Field.descriptor_class">
<code class="descname">descriptor_class</code><a class="headerlink" href="#django.db.models.Field.descriptor_class" title="永久链接至目标">¶</a></dt>
<dd><p>一个实现 <a class="reference external" href="https://docs.python.org/3/reference/datamodel.html#descriptors" title="(在 Python v3.9)"><span class="xref std std-ref">描述符协议</span></a> 的类，它被实例化并分配给模型实例属性。构造函数必须接受一个参数，即 <code class="docutils literal notranslate"><span class="pre">Field</span></code> 实例。覆盖该类属性可以自定义获取和设置行为。</p>
</dd></dl>

<p>为了将一个 <code class="docutils literal notranslate"><span class="pre">Field</span></code> 映射到数据库的特定类型，Django 提供了一些方法：</p>
<dl class="method">
<dt id="django.db.models.Field.get_internal_type">
<code class="descname">get_internal_type</code>()<a class="headerlink" href="#django.db.models.Field.get_internal_type" title="永久链接至目标">¶</a></dt>
<dd><p>返回一个字符串，用于命名这个字段，以满足后台的特定目的。默认情况下，它返回的是类名。</p>
<p>参见 <a class="reference internal" href="../../howto/custom-model-fields.html#emulating-built-in-field-types"><span class="std std-ref">仿造内置字段类型</span></a> 在自定义字段中的用法。</p>
</dd></dl>

<dl class="method">
<dt id="django.db.models.Field.db_type">
<code class="descname">db_type</code>(<em>connection</em>)<a class="headerlink" href="#django.db.models.Field.db_type" title="永久链接至目标">¶</a></dt>
<dd><p>返回 <a class="reference internal" href="#django.db.models.Field" title="django.db.models.Field"><code class="xref py py-class docutils literal notranslate"><span class="pre">Field</span></code></a> 的数据库列数据类型，并考虑 <code class="docutils literal notranslate"><span class="pre">connection</span></code>。</p>
<p>参见 <a class="reference internal" href="../../howto/custom-model-fields.html#custom-database-types"><span class="std std-ref">自定义数据库类型</span></a> 在自定义字段中的用法。</p>
</dd></dl>

<dl class="method">
<dt id="django.db.models.Field.rel_db_type">
<code class="descname">rel_db_type</code>(<em>connection</em>)<a class="headerlink" href="#django.db.models.Field.rel_db_type" title="永久链接至目标">¶</a></dt>
<dd><p>返回指向 <a class="reference internal" href="#django.db.models.Field" title="django.db.models.Field"><code class="xref py py-class docutils literal notranslate"><span class="pre">Field</span></code></a> 的 <code class="docutils literal notranslate"><span class="pre">ForeignKey</span></code> 和 <code class="docutils literal notranslate"><span class="pre">OneToOneField</span></code> 等字段的数据库列数据类型，并考虑 <code class="docutils literal notranslate"><span class="pre">connection</span></code>。</p>
<p>参见 <a class="reference internal" href="../../howto/custom-model-fields.html#custom-database-types"><span class="std std-ref">自定义数据库类型</span></a> 在自定义字段中的用法。</p>
</dd></dl>

<p>Django 主要有三种情况需要与数据库后台和字段进行交互。</p>
<ul class="simple">
<li>当它查询数据库时（Python 值 -&gt; 数据库后台值）</li>
<li>当它从数据库中加载数据时（数据库后台值 -&gt; Python 值）</li>
<li>当它保存到数据库时（Python 值 -&gt; 数据库后端值）</li>
</ul>
<p>查询时，使用 <a class="reference internal" href="#django.db.models.Field.get_db_prep_value" title="django.db.models.Field.get_db_prep_value"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_db_prep_value()</span></code></a> 和 <a class="reference internal" href="#django.db.models.Field.get_prep_value" title="django.db.models.Field.get_prep_value"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_prep_value()</span></code></a>。</p>
<dl class="method">
<dt id="django.db.models.Field.get_prep_value">
<code class="descname">get_prep_value</code>(<em>value</em>)<a class="headerlink" href="#django.db.models.Field.get_prep_value" title="永久链接至目标">¶</a></dt>
<dd><p><code class="docutils literal notranslate"><span class="pre">value</span></code> 是模型属性的当前值，该方法应以准备作为查询参数的格式返回数据。</p>
<p>见 <a class="reference internal" href="../../howto/custom-model-fields.html#converting-python-objects-to-query-values"><span class="std std-ref">将 Python 转为查询值</span></a> 的用法。</p>
</dd></dl>

<dl class="method">
<dt id="django.db.models.Field.get_db_prep_value">
<code class="descname">get_db_prep_value</code>(<em>value</em>, <em>connection</em>, <em>prepared=False</em>)<a class="headerlink" href="#django.db.models.Field.get_db_prep_value" title="永久链接至目标">¶</a></dt>
<dd><p>将 <code class="docutils literal notranslate"><span class="pre">value</span></code> 转换为后台特定的值，默认情况下，如果 <code class="docutils literal notranslate"><span class="pre">prepared=True</span></code>，则返回 <code class="docutils literal notranslate"><span class="pre">value</span></code>。默认情况下，如果 <code class="docutils literal notranslate"><span class="pre">prepared=True</span></code>，它将返回 <code class="docutils literal notranslate"><span class="pre">value</span></code>，而如果是 <code class="docutils literal notranslate"><span class="pre">False</span></code>，它将返回 <a class="reference internal" href="#django.db.models.Field.get_prep_value" title="django.db.models.Field.get_prep_value"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_prep_value()</span></code></a> 。</p>
<p>使用方法参见 <a class="reference internal" href="../../howto/custom-model-fields.html#converting-query-values-to-database-values"><span class="std std-ref">将查询值转为数据库值</span></a>。</p>
</dd></dl>

<p>加载数据时，使用 <a class="reference internal" href="#django.db.models.Field.from_db_value" title="django.db.models.Field.from_db_value"><code class="xref py py-meth docutils literal notranslate"><span class="pre">from_db_value()</span></code></a>。</p>
<dl class="method">
<dt id="django.db.models.Field.from_db_value">
<code class="descname">from_db_value</code>(<em>value</em>, <em>expression</em>, <em>connection</em>)<a class="headerlink" href="#django.db.models.Field.from_db_value" title="永久链接至目标">¶</a></dt>
<dd><p>将数据库返回的值转换为 Python 对象。与 <a class="reference internal" href="#django.db.models.Field.get_prep_value" title="django.db.models.Field.get_prep_value"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_prep_value()</span></code></a> 相反。</p>
<p>这个方法不用于大多数内置字段，因为数据库后端已经返回了正确的 Python 类型，或者后端自己进行了转换。</p>
<p><code class="docutils literal notranslate"><span class="pre">expression</span></code> 与 <code class="docutils literal notranslate"><span class="pre">self</span></code> 相同。</p>
<p>使用方法参见 <a class="reference internal" href="../../howto/custom-model-fields.html#converting-values-to-python-objects"><span class="std std-ref">将值转为 Python 对象</span></a>。</p>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">由于性能原因，<code class="docutils literal notranslate"><span class="pre">from_db_value</span></code> 并没有在不需要它的字段上实现 no-op（所有 Django 字段）。因此，你不能在定义中调用 <code class="docutils literal notranslate"><span class="pre">super</span></code>。</p>
</div>
</dd></dl>

<p>保存时，使用 <a class="reference internal" href="#django.db.models.Field.pre_save" title="django.db.models.Field.pre_save"><code class="xref py py-meth docutils literal notranslate"><span class="pre">pre_save()</span></code></a> 和 <a class="reference internal" href="#django.db.models.Field.get_db_prep_save" title="django.db.models.Field.get_db_prep_save"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_db_prep_save()</span></code></a> ：</p>
<dl class="method">
<dt id="django.db.models.Field.get_db_prep_save">
<code class="descname">get_db_prep_save</code>(<em>value</em>, <em>connection</em>)<a class="headerlink" href="#django.db.models.Field.get_db_prep_save" title="永久链接至目标">¶</a></dt>
<dd><p>与 <a class="reference internal" href="#django.db.models.Field.get_db_prep_value" title="django.db.models.Field.get_db_prep_value"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_db_prep_value()</span></code></a> 相同，但当字段值必须 <em>保存</em> 到数据库中时，会被调用。默认情况下返回 <a class="reference internal" href="#django.db.models.Field.get_db_prep_value" title="django.db.models.Field.get_db_prep_value"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_db_prep_value()</span></code></a>。</p>
</dd></dl>

<dl class="method">
<dt id="django.db.models.Field.pre_save">
<code class="descname">pre_save</code>(<em>model_instance</em>, <em>add</em>)<a class="headerlink" href="#django.db.models.Field.pre_save" title="永久链接至目标">¶</a></dt>
<dd><p>在 <a class="reference internal" href="#django.db.models.Field.get_db_prep_save" title="django.db.models.Field.get_db_prep_save"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_db_prep_save()</span></code></a> 之前调用的方法，在保存前准备好值（例如 <a class="reference internal" href="#django.db.models.DateField.auto_now" title="django.db.models.DateField.auto_now"><code class="xref py py-attr docutils literal notranslate"><span class="pre">DateField.auto_now</span></code></a> ）。</p>
<p><code class="docutils literal notranslate"><span class="pre">model_instance</span></code> 是该字段所属的实例，<code class="docutils literal notranslate"><span class="pre">add</span></code> 是该实例是否第一次被保存到数据库中。</p>
<p>它应该从 <code class="docutils literal notranslate"><span class="pre">model_instance</span></code> 中返回这个字段的适当属性的值。属性名在 <code class="docutils literal notranslate"><span class="pre">self.attname</span></code> 中（这是由 <a class="reference internal" href="#django.db.models.Field" title="django.db.models.Field"><code class="xref py py-class docutils literal notranslate"><span class="pre">Field</span></code></a> 设置的）。</p>
<p>使用方法参见 <a class="reference internal" href="../../howto/custom-model-fields.html#preprocessing-values-before-saving"><span class="std std-ref">在保存前预处理数值</span></a>。</p>
</dd></dl>

<p>字段经常以不同的类型接收它们的值，要么来自序列化，要么来自表单。</p>
<dl class="method">
<dt id="django.db.models.Field.to_python">
<code class="descname">to_python</code>(<em>value</em>)<a class="headerlink" href="#django.db.models.Field.to_python" title="永久链接至目标">¶</a></dt>
<dd><p>将值转换为正确的 Python 对象。它的作用与 <a class="reference internal" href="#django.db.models.Field.value_to_string" title="django.db.models.Field.value_to_string"><code class="xref py py-meth docutils literal notranslate"><span class="pre">value_to_string()</span></code></a> 相反，并且在 <a class="reference internal" href="instances.html#django.db.models.Model.clean" title="django.db.models.Model.clean"><code class="xref py py-meth docutils literal notranslate"><span class="pre">clean()</span></code></a> 中也被调用。</p>
<p>使用方法参见 <a class="reference internal" href="../../howto/custom-model-fields.html#converting-values-to-python-objects"><span class="std std-ref">将值转为 Python 对象</span></a>。</p>
</dd></dl>

<p>除了保存到数据库，字段还需要知道如何将其值序列化。</p>
<dl class="method">
<dt id="django.db.models.Field.value_from_object">
<code class="descname">value_from_object</code>(<em>obj</em>)<a class="headerlink" href="#django.db.models.Field.value_from_object" title="永久链接至目标">¶</a></dt>
<dd><p>返回给定模型实例的字段值。</p>
<p>这个方法经常被 <a class="reference internal" href="#django.db.models.Field.value_to_string" title="django.db.models.Field.value_to_string"><code class="xref py py-meth docutils literal notranslate"><span class="pre">value_to_string()</span></code></a> 使用。</p>
</dd></dl>

<dl class="method">
<dt id="django.db.models.Field.value_to_string">
<code class="descname">value_to_string</code>(<em>obj</em>)<a class="headerlink" href="#django.db.models.Field.value_to_string" title="永久链接至目标">¶</a></dt>
<dd><p>将 <code class="docutils literal notranslate"><span class="pre">obj</span></code> 转换为字符串。用于序列化字段的值。</p>
<p>使用方法参见 <a class="reference internal" href="../../howto/custom-model-fields.html#converting-model-field-to-serialization"><span class="std std-ref">为序列化转换字段数据</span></a>。</p>
</dd></dl>

<p>当使用 <a class="reference internal" href="../../topics/forms/modelforms.html#django.forms.ModelForm" title="django.forms.ModelForm"><code class="xref py py-class docutils literal notranslate"><span class="pre">model</span> <span class="pre">forms</span></code></a> 时，<code class="docutils literal notranslate"><span class="pre">Field</span></code> 需要知道它应该由哪个表单字段来表示。</p>
<dl class="method">
<dt id="django.db.models.Field.formfield">
<code class="descname">formfield</code>(<em>form_class=None</em>, <em>choices_form_class=None</em>, <em>**kwargs</em>)<a class="headerlink" href="#django.db.models.Field.formfield" title="永久链接至目标">¶</a></dt>
<dd><p>返回该字段默认的 <a class="reference internal" href="../forms/fields.html#django.forms.Field" title="django.forms.Field"><code class="xref py py-class docutils literal notranslate"><span class="pre">django.forms.Field</span></code></a> 给 <a class="reference internal" href="../../topics/forms/modelforms.html#django.forms.ModelForm" title="django.forms.ModelForm"><code class="xref py py-class docutils literal notranslate"><span class="pre">ModelForm</span></code></a>。</p>
<p>默认情况下，如果 <code class="docutils literal notranslate"><span class="pre">form_class</span></code> 和 <code class="docutils literal notranslate"><span class="pre">choices_form_class</span></code> 都是 <code class="docutils literal notranslate"><span class="pre">None</span></code>，则使用 <a class="reference internal" href="../forms/fields.html#django.forms.CharField" title="django.forms.CharField"><code class="xref py py-class docutils literal notranslate"><span class="pre">CharField</span></code></a>。如果字段有 <code class="xref py py-attr docutils literal notranslate"><span class="pre">chips</span></code>，且 <code class="docutils literal notranslate"><span class="pre">choices_form_class</span></code> 没有指定，则使用 <a class="reference internal" href="../forms/fields.html#django.forms.TypedChoiceField" title="django.forms.TypedChoiceField"><code class="xref py py-class docutils literal notranslate"><span class="pre">TypedChoiceField</span></code></a>。</p>
<p>使用方法参见 <a class="reference internal" href="../../howto/custom-model-fields.html#specifying-form-field-for-model-field"><span class="std std-ref">为模型字段指定表单字段</span></a>。</p>
</dd></dl>

<dl class="method">
<dt id="django.db.models.Field.deconstruct">
<code class="descname">deconstruct</code>()<a class="headerlink" href="#django.db.models.Field.deconstruct" title="永久链接至目标">¶</a></dt>
<dd><p>返回一个包含足够信息的四元元组来重新创建字段。</p>
<ol class="arabic simple">
<li>模型上的字段名称。</li>
<li>字段的导入路径（例如 <code class="docutils literal notranslate"><span class="pre">&quot;django.db.models.IntegerField&quot;</span></code> ）。这应该是最可移植版本，所以不那么具体可能更好。</li>
<li>一个位置参数的列表。</li>
<li>一个关键字参数的字典。</li>
</ol>
<p>这个方法必须添加到 1.7 之前的字段中，才能使用 <a class="reference internal" href="../../topics/migrations.html"><span class="doc">Migrations</span></a> 迁移其数据。</p>
</dd></dl>

</dd></dl>

</div>
</div>
<div class="section" id="s-field-attribute-reference">
<span id="s-model-field-attributes"></span><span id="field-attribute-reference"></span><span id="model-field-attributes"></span><h1>字段属性参考<a class="headerlink" href="#field-attribute-reference" title="永久链接至标题">¶</a></h1>
<p>每个 <code class="docutils literal notranslate"><span class="pre">Field</span></code> 实例都包含几个属性，允许对其行为进行内省。当你需要编写依赖于字段功能的代码时，可以使用这些属性来代替 <code class="docutils literal notranslate"><span class="pre">isinstance</span></code> 检查。这些属性可以与 <a class="reference internal" href="meta.html#model-meta-field-api"><span class="std std-ref">Model._meta API</span></a> 一起使用，以缩小对特定字段类型的搜索范围。自定义模型字段应该实现这些标志。</p>
<div class="section" id="s-attributes-for-fields">
<span id="attributes-for-fields"></span><h2>字段的属性<a class="headerlink" href="#attributes-for-fields" title="永久链接至标题">¶</a></h2>
<dl class="attribute">
<dt id="django.db.models.Field.auto_created">
<code class="descclassname">Field.</code><code class="descname">auto_created</code><a class="headerlink" href="#django.db.models.Field.auto_created" title="永久链接至目标">¶</a></dt>
<dd><p>表示是否自动创建字段的布尔标志，如模型继承使用的 <code class="docutils literal notranslate"><span class="pre">OneToOneField</span></code>。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.db.models.Field.concrete">
<code class="descclassname">Field.</code><code class="descname">concrete</code><a class="headerlink" href="#django.db.models.Field.concrete" title="永久链接至目标">¶</a></dt>
<dd><p>布尔值标志，表示该字段是否有与之相关的数据库列。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.db.models.Field.hidden">
<code class="descclassname">Field.</code><code class="descname">hidden</code><a class="headerlink" href="#django.db.models.Field.hidden" title="永久链接至目标">¶</a></dt>
<dd><p>布尔值标志，表示一个字段是否用于支持另一个非隐藏字段的功能（例如，组成 <code class="docutils literal notranslate"><span class="pre">GenericForeignKey</span></code> 的 <code class="docutils literal notranslate"><span class="pre">content_type</span></code> 和 <code class="docutils literal notranslate"><span class="pre">object_id</span></code> 字段）。<code class="docutils literal notranslate"><span class="pre">hidden</span></code> 标志用于区分构成模型上公共字段子集的内容和模型上所有字段。</p>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last"><a class="reference internal" href="meta.html#django.db.models.options.Options.get_fields" title="django.db.models.options.Options.get_fields"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Options.get_fields()</span></code></a> 默认情况下不包括隐藏字段。传入 <code class="docutils literal notranslate"><span class="pre">include_hidden=True</span></code> 在结果中返回隐藏字段。</p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="django.db.models.Field.is_relation">
<code class="descclassname">Field.</code><code class="descname">is_relation</code><a class="headerlink" href="#django.db.models.Field.is_relation" title="永久链接至目标">¶</a></dt>
<dd><p>布尔值标志，表示一个字段是否包含对一个或多个其他模型的功能引用（如 <code class="docutils literal notranslate"><span class="pre">ForeignKey</span></code>、<code class="docutils literal notranslate"><span class="pre">ManyToManyField</span></code>、<code class="docutils literal notranslate"><span class="pre">OneToOneField</span></code> 等）。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.db.models.Field.model">
<code class="descclassname">Field.</code><code class="descname">model</code><a class="headerlink" href="#django.db.models.Field.model" title="永久链接至目标">¶</a></dt>
<dd><p>返回定义字段的模型。如果一个字段定义在一个模型的超类上，<code class="docutils literal notranslate"><span class="pre">model</span></code> 将指的是超类，而不是实例的类。</p>
</dd></dl>

</div>
<div class="section" id="s-attributes-for-fields-with-relations">
<span id="attributes-for-fields-with-relations"></span><h2>有关系的字段的属性<a class="headerlink" href="#attributes-for-fields-with-relations" title="永久链接至标题">¶</a></h2>
<p>这些属性用于查询关系的基数和其他细节。这些属性在所有字段上都存在；但是，如果字段是关系类型（ <a class="reference internal" href="#django.db.models.Field.is_relation" title="django.db.models.Field.is_relation"><code class="xref py py-attr docutils literal notranslate"><span class="pre">Field.is_relation=True</span></code></a> ），它们只有布尔值（而不是 <code class="docutils literal notranslate"><span class="pre">None</span></code> ）。</p>
<dl class="attribute">
<dt id="django.db.models.Field.many_to_many">
<code class="descclassname">Field.</code><code class="descname">many_to_many</code><a class="headerlink" href="#django.db.models.Field.many_to_many" title="永久链接至目标">¶</a></dt>
<dd><p>如果字段有多对多关系，则为 <code class="docutils literal notranslate"><span class="pre">True</span></code>，否则为 <code class="docutils literal notranslate"><span class="pre">False</span></code>。Django 中唯一一个是 <code class="docutils literal notranslate"><span class="pre">True</span></code> 的字段是 <code class="docutils literal notranslate"><span class="pre">ManyToManyField</span></code>。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.db.models.Field.many_to_one">
<code class="descclassname">Field.</code><code class="descname">many_to_one</code><a class="headerlink" href="#django.db.models.Field.many_to_one" title="永久链接至目标">¶</a></dt>
<dd><p>如果字段有多对一关系，如 <code class="docutils literal notranslate"><span class="pre">ForeignKey</span></code>，则为 <code class="docutils literal notranslate"><span class="pre">True</span></code> ；否则为 <code class="docutils literal notranslate"><span class="pre">False</span></code>。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.db.models.Field.one_to_many">
<code class="descclassname">Field.</code><code class="descname">one_to_many</code><a class="headerlink" href="#django.db.models.Field.one_to_many" title="永久链接至目标">¶</a></dt>
<dd><p>如果该字段有一对多关系，如 <code class="docutils literal notranslate"><span class="pre">GenericRelation</span></code> 或 <code class="docutils literal notranslate"><span class="pre">ForeignKey</span></code> 的反向关系，则为 <code class="docutils literal notranslate"><span class="pre">True</span></code> ；否则为 <code class="docutils literal notranslate"><span class="pre">False</span></code>。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.db.models.Field.one_to_one">
<code class="descclassname">Field.</code><code class="descname">one_to_one</code><a class="headerlink" href="#django.db.models.Field.one_to_one" title="永久链接至目标">¶</a></dt>
<dd><p>如果字段有一对一的关系，如 <code class="docutils literal notranslate"><span class="pre">OneToOneField</span></code>，则为 <code class="docutils literal notranslate"><span class="pre">True</span></code> ；否则为 <code class="docutils literal notranslate"><span class="pre">False</span></code>。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.db.models.Field.related_model">
<code class="descclassname">Field.</code><code class="descname">related_model</code><a class="headerlink" href="#django.db.models.Field.related_model" title="永久链接至目标">¶</a></dt>
<dd><p>指向该字段所涉及的模型。例如，<code class="docutils literal notranslate"><span class="pre">ForeignKey(Author,</span> <span class="pre">on_delete=models.CASCADE)</span></code> 中的 <code class="docutils literal notranslate"><span class="pre">Author</span></code>。<code class="docutils literal notranslate"><span class="pre">GenericForeignKey</span></code> 的 <code class="docutils literal notranslate"><span class="pre">related_model</span></code> 总是 <code class="docutils literal notranslate"><span class="pre">None</span></code>。</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">模型字段参考</a><ul>
<li><a class="reference internal" href="#field-options">字段选项</a><ul>
<li><a class="reference internal" href="#null"><code class="docutils literal notranslate"><span class="pre">null</span></code></a></li>
<li><a class="reference internal" href="#blank"><code class="docutils literal notranslate"><span class="pre">blank</span></code></a></li>
<li><a class="reference internal" href="#choices"><code class="docutils literal notranslate"><span class="pre">choices</span></code></a><ul>
<li><a class="reference internal" href="#enumeration-types">枚举类型</a></li>
</ul>
</li>
<li><a class="reference internal" href="#db-column"><code class="docutils literal notranslate"><span class="pre">db_column</span></code></a></li>
<li><a class="reference internal" href="#db-index"><code class="docutils literal notranslate"><span class="pre">db_index</span></code></a></li>
<li><a class="reference internal" href="#db-tablespace"><code class="docutils literal notranslate"><span class="pre">db_tablespace</span></code></a></li>
<li><a class="reference internal" href="#default"><code class="docutils literal notranslate"><span class="pre">default</span></code></a></li>
<li><a class="reference internal" href="#editable"><code class="docutils literal notranslate"><span class="pre">editable</span></code></a></li>
<li><a class="reference internal" href="#error-messages"><code class="docutils literal notranslate"><span class="pre">error_messages</span></code></a></li>
<li><a class="reference internal" href="#help-text"><code class="docutils literal notranslate"><span class="pre">help_text</span></code></a></li>
<li><a class="reference internal" href="#primary-key"><code class="docutils literal notranslate"><span class="pre">primary_key</span></code></a></li>
<li><a class="reference internal" href="#unique"><code class="docutils literal notranslate"><span class="pre">unique</span></code></a></li>
<li><a class="reference internal" href="#unique-for-date"><code class="docutils literal notranslate"><span class="pre">unique_for_date</span></code></a></li>
<li><a class="reference internal" href="#unique-for-month"><code class="docutils literal notranslate"><span class="pre">unique_for_month</span></code></a></li>
<li><a class="reference internal" href="#unique-for-year"><code class="docutils literal notranslate"><span class="pre">unique_for_year</span></code></a></li>
<li><a class="reference internal" href="#verbose-name"><code class="docutils literal notranslate"><span class="pre">verbose_name</span></code></a></li>
<li><a class="reference internal" href="#validators"><code class="docutils literal notranslate"><span class="pre">validators</span></code></a><ul>
<li><a class="reference internal" href="#registering-and-fetching-lookups">注册和获取查询</a></li>
</ul>
</li>
</ul>
</li>
<li><a class="reference internal" href="#field-types">字段类型</a><ul>
<li><a class="reference internal" href="#autofield"><code class="docutils literal notranslate"><span class="pre">AutoField</span></code></a></li>
<li><a class="reference internal" href="#bigautofield"><code class="docutils literal notranslate"><span class="pre">BigAutoField</span></code></a></li>
<li><a class="reference internal" href="#bigintegerfield"><code class="docutils literal notranslate"><span class="pre">BigIntegerField</span></code></a></li>
<li><a class="reference internal" href="#binaryfield"><code class="docutils literal notranslate"><span class="pre">BinaryField</span></code></a></li>
<li><a class="reference internal" href="#booleanfield"><code class="docutils literal notranslate"><span class="pre">BooleanField</span></code></a></li>
<li><a class="reference internal" href="#charfield"><code class="docutils literal notranslate"><span class="pre">CharField</span></code></a></li>
<li><a class="reference internal" href="#datefield"><code class="docutils literal notranslate"><span class="pre">DateField</span></code></a></li>
<li><a class="reference internal" href="#datetimefield"><code class="docutils literal notranslate"><span class="pre">DateTimeField</span></code></a></li>
<li><a class="reference internal" href="#decimalfield"><code class="docutils literal notranslate"><span class="pre">DecimalField</span></code></a></li>
<li><a class="reference internal" href="#durationfield"><code class="docutils literal notranslate"><span class="pre">DurationField</span></code></a></li>
<li><a class="reference internal" href="#emailfield"><code class="docutils literal notranslate"><span class="pre">EmailField</span></code></a></li>
<li><a class="reference internal" href="#filefield"><code class="docutils literal notranslate"><span class="pre">FileField</span></code></a><ul>
<li><a class="reference internal" href="#filefield-and-fieldfile"><code class="docutils literal notranslate"><span class="pre">FileField</span></code> 和 <code class="docutils literal notranslate"><span class="pre">FieldFile</span></code></a></li>
</ul>
</li>
<li><a class="reference internal" href="#filepathfield"><code class="docutils literal notranslate"><span class="pre">FilePathField</span></code></a></li>
<li><a class="reference internal" href="#floatfield"><code class="docutils literal notranslate"><span class="pre">FloatField</span></code></a></li>
<li><a class="reference internal" href="#imagefield"><code class="docutils literal notranslate"><span class="pre">ImageField</span></code></a></li>
<li><a class="reference internal" href="#integerfield"><code class="docutils literal notranslate"><span class="pre">IntegerField</span></code></a></li>
<li><a class="reference internal" href="#genericipaddressfield"><code class="docutils literal notranslate"><span class="pre">GenericIPAddressField</span></code></a></li>
<li><a class="reference internal" href="#jsonfield"><code class="docutils literal notranslate"><span class="pre">JSONField</span></code></a></li>
<li><a class="reference internal" href="#nullbooleanfield"><code class="docutils literal notranslate"><span class="pre">NullBooleanField</span></code></a></li>
<li><a class="reference internal" href="#positivebigintegerfield"><code class="docutils literal notranslate"><span class="pre">PositiveBigIntegerField</span></code></a></li>
<li><a class="reference internal" href="#positiveintegerfield"><code class="docutils literal notranslate"><span class="pre">PositiveIntegerField</span></code></a></li>
<li><a class="reference internal" href="#positivesmallintegerfield"><code class="docutils literal notranslate"><span class="pre">PositiveSmallIntegerField</span></code></a></li>
<li><a class="reference internal" href="#slugfield"><code class="docutils literal notranslate"><span class="pre">SlugField</span></code></a></li>
<li><a class="reference internal" href="#smallautofield"><code class="docutils literal notranslate"><span class="pre">SmallAutoField</span></code></a></li>
<li><a class="reference internal" href="#smallintegerfield"><code class="docutils literal notranslate"><span class="pre">SmallIntegerField</span></code></a></li>
<li><a class="reference internal" href="#textfield"><code class="docutils literal notranslate"><span class="pre">TextField</span></code></a></li>
<li><a class="reference internal" href="#timefield"><code class="docutils literal notranslate"><span class="pre">TimeField</span></code></a></li>
<li><a class="reference internal" href="#urlfield"><code class="docutils literal notranslate"><span class="pre">URLField</span></code></a></li>
<li><a class="reference internal" href="#uuidfield"><code class="docutils literal notranslate"><span class="pre">UUIDField</span></code></a></li>
</ul>
</li>
<li><a class="reference internal" href="#module-django.db.models.fields.related">关系字段</a><ul>
<li><a class="reference internal" href="#foreignkey"><code class="docutils literal notranslate"><span class="pre">ForeignKey</span></code></a><ul>
<li><a class="reference internal" href="#database-representation">数据库表现</a></li>
<li><a class="reference internal" href="#arguments">参数</a></li>
</ul>
</li>
<li><a class="reference internal" href="#manytomanyfield"><code class="docutils literal notranslate"><span class="pre">ManyToManyField</span></code></a><ul>
<li><a class="reference internal" href="#id1">数据库表现</a></li>
<li><a class="reference internal" href="#manytomany-arguments">参数</a></li>
</ul>
</li>
<li><a class="reference internal" href="#onetoonefield"><code class="docutils literal notranslate"><span class="pre">OneToOneField</span></code></a></li>
</ul>
</li>
<li><a class="reference internal" href="#field-api-reference">字段 API 参考</a></li>
</ul>
</li>
<li><a class="reference internal" href="#field-attribute-reference">字段属性参考</a><ul>
<li><a class="reference internal" href="#attributes-for-fields">字段的属性</a></li>
<li><a class="reference internal" href="#attributes-for-fields-with-relations">有关系的字段的属性</a></li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="index.html"
                        title="上一章">模型</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="indexes.html"
                        title="下一章">模型索引参考</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../../_sources/ref/models/fields.txt"
            rel="nofollow">显示源代码</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>快速搜索</h3>
    <div class="searchformwrapper">
    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="转向" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">7月 23, 2021</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="index.html" title="模型">previous</a>
     |
    <a href="../index.html" title="API 参考" accesskey="U">up</a>
   |
    <a href="indexes.html" title="模型索引参考">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>